es6.js 4.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines defines the current define statements for the shader.
  65. * @param effect defines the current effect we try to compile
  66. * @returns The resulting defines with defines of the current rank removed.
  67. */
  68. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  69. // First we try to switch to CPU skinning
  70. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  71. this._mesh.computeBonesUsingShaders = false;
  72. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  73. effect._bonesComputationForcedToCPU = true;
  74. var scene = this._mesh.getScene();
  75. for (var index = 0; index < scene.meshes.length; index++) {
  76. var otherMesh = scene.meshes[index];
  77. if (!otherMesh.material) {
  78. continue;
  79. }
  80. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  81. continue;
  82. }
  83. if (otherMesh.material.getEffect() === effect) {
  84. otherMesh.computeBonesUsingShaders = false;
  85. }
  86. else if (otherMesh.subMeshes) {
  87. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  88. var subMesh = _a[_i];
  89. var subMeshEffect = subMesh.effect;
  90. if (subMeshEffect === effect) {
  91. otherMesh.computeBonesUsingShaders = false;
  92. break;
  93. }
  94. }
  95. }
  96. }
  97. }
  98. else {
  99. var currentFallbacks = this._defines[this._currentRank];
  100. if (currentFallbacks) {
  101. for (var index = 0; index < currentFallbacks.length; index++) {
  102. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  103. }
  104. }
  105. this._currentRank++;
  106. }
  107. return currentDefines;
  108. };
  109. return EffectFallbacks;
  110. }());
  111. BABYLON.EffectFallbacks = EffectFallbacks;
  112. /**
  113. * Options to be used when creating an effect.
  114. */
  115. var EffectCreationOptions = /** @class */ (function () {
  116. function EffectCreationOptions() {
  117. }
  118. return EffectCreationOptions;
  119. }());
  120. BABYLON.EffectCreationOptions = EffectCreationOptions;
  121. /**
  122. * Effect containing vertex and fragment shader that can be executed on an object.
  123. */
  124. var Effect = /** @class */ (function () {
  125. /**
  126. * Instantiates an effect.
  127. * An effect can be used to create/manage/execute vertex and fragment shaders.
  128. * @param baseName Name of the effect.
  129. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  130. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  131. * @param samplers List of sampler variables that will be passed to the shader.
  132. * @param engine Engine to be used to render the effect
  133. * @param defines Define statements to be added to the shader.
  134. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  135. * @param onCompiled Callback that will be called when the shader is compiled.
  136. * @param onError Callback that will be called if an error occurs during shader compilation.
  137. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  138. */
  139. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  140. if (samplers === void 0) { samplers = null; }
  141. if (defines === void 0) { defines = null; }
  142. if (fallbacks === void 0) { fallbacks = null; }
  143. if (onCompiled === void 0) { onCompiled = null; }
  144. if (onError === void 0) { onError = null; }
  145. var _this = this;
  146. /**
  147. * Unique ID of the effect.
  148. */
  149. this.uniqueId = 0;
  150. /**
  151. * Observable that will be called when the shader is compiled.
  152. */
  153. this.onCompileObservable = new BABYLON.Observable();
  154. /**
  155. * Observable that will be called if an error occurs during shader compilation.
  156. */
  157. this.onErrorObservable = new BABYLON.Observable();
  158. /**
  159. * Observable that will be called when effect is bound.
  160. */
  161. this.onBindObservable = new BABYLON.Observable();
  162. /** @hidden */
  163. this._bonesComputationForcedToCPU = false;
  164. this._uniformBuffersNames = {};
  165. this._isReady = false;
  166. this._compilationError = "";
  167. this.name = baseName;
  168. if (attributesNamesOrOptions.attributes) {
  169. var options = attributesNamesOrOptions;
  170. this._engine = uniformsNamesOrEngine;
  171. this._attributesNames = options.attributes;
  172. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  173. this._samplers = options.samplers.slice();
  174. this.defines = options.defines;
  175. this.onError = options.onError;
  176. this.onCompiled = options.onCompiled;
  177. this._fallbacks = options.fallbacks;
  178. this._indexParameters = options.indexParameters;
  179. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  180. if (options.uniformBuffersNames) {
  181. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  182. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  183. }
  184. }
  185. }
  186. else {
  187. this._engine = engine;
  188. this.defines = defines;
  189. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  190. this._samplers = samplers ? samplers.slice() : [];
  191. this._attributesNames = attributesNamesOrOptions;
  192. this.onError = onError;
  193. this.onCompiled = onCompiled;
  194. this._indexParameters = indexParameters;
  195. this._fallbacks = fallbacks;
  196. }
  197. this.uniqueId = Effect._uniqueIdSeed++;
  198. var vertexSource;
  199. var fragmentSource;
  200. if (baseName.vertexElement) {
  201. vertexSource = document.getElementById(baseName.vertexElement);
  202. if (!vertexSource) {
  203. vertexSource = baseName.vertexElement;
  204. }
  205. }
  206. else {
  207. vertexSource = baseName.vertex || baseName;
  208. }
  209. if (baseName.fragmentElement) {
  210. fragmentSource = document.getElementById(baseName.fragmentElement);
  211. if (!fragmentSource) {
  212. fragmentSource = baseName.fragmentElement;
  213. }
  214. }
  215. else {
  216. fragmentSource = baseName.fragment || baseName;
  217. }
  218. this._loadVertexShader(vertexSource, function (vertexCode) {
  219. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  220. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  221. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  222. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  223. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  224. if (baseName) {
  225. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  226. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  227. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  228. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  229. }
  230. else {
  231. _this._vertexSourceCode = migratedVertexCode;
  232. _this._fragmentSourceCode = migratedFragmentCode;
  233. }
  234. _this._prepareEffect();
  235. });
  236. });
  237. });
  238. });
  239. });
  240. });
  241. }
  242. Object.defineProperty(Effect.prototype, "key", {
  243. /**
  244. * Unique key for this effect
  245. */
  246. get: function () {
  247. return this._key;
  248. },
  249. enumerable: true,
  250. configurable: true
  251. });
  252. /**
  253. * If the effect has been compiled and prepared.
  254. * @returns if the effect is compiled and prepared.
  255. */
  256. Effect.prototype.isReady = function () {
  257. return this._isReady;
  258. };
  259. /**
  260. * The engine the effect was initialized with.
  261. * @returns the engine.
  262. */
  263. Effect.prototype.getEngine = function () {
  264. return this._engine;
  265. };
  266. /**
  267. * The compiled webGL program for the effect
  268. * @returns the webGL program.
  269. */
  270. Effect.prototype.getProgram = function () {
  271. return this._program;
  272. };
  273. /**
  274. * The set of names of attribute variables for the shader.
  275. * @returns An array of attribute names.
  276. */
  277. Effect.prototype.getAttributesNames = function () {
  278. return this._attributesNames;
  279. };
  280. /**
  281. * Returns the attribute at the given index.
  282. * @param index The index of the attribute.
  283. * @returns The location of the attribute.
  284. */
  285. Effect.prototype.getAttributeLocation = function (index) {
  286. return this._attributes[index];
  287. };
  288. /**
  289. * Returns the attribute based on the name of the variable.
  290. * @param name of the attribute to look up.
  291. * @returns the attribute location.
  292. */
  293. Effect.prototype.getAttributeLocationByName = function (name) {
  294. var index = this._attributesNames.indexOf(name);
  295. return this._attributes[index];
  296. };
  297. /**
  298. * The number of attributes.
  299. * @returns the numnber of attributes.
  300. */
  301. Effect.prototype.getAttributesCount = function () {
  302. return this._attributes.length;
  303. };
  304. /**
  305. * Gets the index of a uniform variable.
  306. * @param uniformName of the uniform to look up.
  307. * @returns the index.
  308. */
  309. Effect.prototype.getUniformIndex = function (uniformName) {
  310. return this._uniformsNames.indexOf(uniformName);
  311. };
  312. /**
  313. * Returns the attribute based on the name of the variable.
  314. * @param uniformName of the uniform to look up.
  315. * @returns the location of the uniform.
  316. */
  317. Effect.prototype.getUniform = function (uniformName) {
  318. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  319. };
  320. /**
  321. * Returns an array of sampler variable names
  322. * @returns The array of sampler variable neames.
  323. */
  324. Effect.prototype.getSamplers = function () {
  325. return this._samplers;
  326. };
  327. /**
  328. * The error from the last compilation.
  329. * @returns the error string.
  330. */
  331. Effect.prototype.getCompilationError = function () {
  332. return this._compilationError;
  333. };
  334. /**
  335. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  336. * @param func The callback to be used.
  337. */
  338. Effect.prototype.executeWhenCompiled = function (func) {
  339. if (this.isReady()) {
  340. func(this);
  341. return;
  342. }
  343. this.onCompileObservable.add(function (effect) {
  344. func(effect);
  345. });
  346. };
  347. /** @hidden */
  348. Effect.prototype._loadVertexShader = function (vertex, callback) {
  349. if (BABYLON.Tools.IsWindowObjectExist()) {
  350. // DOM element ?
  351. if (vertex instanceof HTMLElement) {
  352. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  353. callback(vertexCode);
  354. return;
  355. }
  356. }
  357. // Base64 encoded ?
  358. if (vertex.substr(0, 7) === "base64:") {
  359. var vertexBinary = window.atob(vertex.substr(7));
  360. callback(vertexBinary);
  361. return;
  362. }
  363. // Is in local store ?
  364. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  365. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  366. return;
  367. }
  368. var vertexShaderUrl;
  369. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  370. vertexShaderUrl = vertex;
  371. }
  372. else {
  373. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  374. }
  375. // Vertex shader
  376. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  377. };
  378. /** @hidden */
  379. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  380. if (BABYLON.Tools.IsWindowObjectExist()) {
  381. // DOM element ?
  382. if (fragment instanceof HTMLElement) {
  383. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  384. callback(fragmentCode);
  385. return;
  386. }
  387. }
  388. // Base64 encoded ?
  389. if (fragment.substr(0, 7) === "base64:") {
  390. var fragmentBinary = window.atob(fragment.substr(7));
  391. callback(fragmentBinary);
  392. return;
  393. }
  394. // Is in local store ?
  395. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  396. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  397. return;
  398. }
  399. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  400. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  401. return;
  402. }
  403. var fragmentShaderUrl;
  404. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  405. fragmentShaderUrl = fragment;
  406. }
  407. else {
  408. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  409. }
  410. // Fragment shader
  411. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  412. };
  413. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  414. // Rebuild shaders source code
  415. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  416. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  417. vertexCode = prefix + vertexCode;
  418. fragmentCode = prefix + fragmentCode;
  419. // Number lines of shaders source code
  420. var i = 2;
  421. var regex = /\n/gm;
  422. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  423. i = 2;
  424. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  425. // Dump shaders name and formatted source code
  426. if (this.name.vertexElement) {
  427. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  428. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  429. }
  430. else if (this.name.vertex) {
  431. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  432. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  433. }
  434. else {
  435. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  436. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  437. }
  438. };
  439. ;
  440. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  441. var preparedSourceCode = this._processPrecision(sourceCode);
  442. if (this._engine.webGLVersion == 1) {
  443. callback(preparedSourceCode);
  444. return;
  445. }
  446. // Already converted
  447. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  448. callback(preparedSourceCode.replace("#version 300 es", ""));
  449. return;
  450. }
  451. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  452. // Remove extensions
  453. // #extension GL_OES_standard_derivatives : enable
  454. // #extension GL_EXT_shader_texture_lod : enable
  455. // #extension GL_EXT_frag_depth : enable
  456. // #extension GL_EXT_draw_buffers : require
  457. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  458. var result = preparedSourceCode.replace(regex, "");
  459. // Migrate to GLSL v300
  460. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  461. result = result.replace(/attribute[ \t]/g, "in ");
  462. result = result.replace(/[ \t]attribute/g, " in");
  463. if (isFragment) {
  464. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  465. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  466. result = result.replace(/texture2D\s*\(/g, "texture(");
  467. result = result.replace(/textureCube\s*\(/g, "texture(");
  468. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  469. result = result.replace(/gl_FragColor/g, "glFragColor");
  470. result = result.replace(/gl_FragData/g, "glFragData");
  471. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  472. }
  473. callback(result);
  474. };
  475. Effect.prototype._processIncludes = function (sourceCode, callback) {
  476. var _this = this;
  477. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  478. var match = regex.exec(sourceCode);
  479. var returnValue = new String(sourceCode);
  480. while (match != null) {
  481. var includeFile = match[1];
  482. // Uniform declaration
  483. if (includeFile.indexOf("__decl__") !== -1) {
  484. includeFile = includeFile.replace(/__decl__/, "");
  485. if (this._engine.supportsUniformBuffers) {
  486. includeFile = includeFile.replace(/Vertex/, "Ubo");
  487. includeFile = includeFile.replace(/Fragment/, "Ubo");
  488. }
  489. includeFile = includeFile + "Declaration";
  490. }
  491. if (Effect.IncludesShadersStore[includeFile]) {
  492. // Substitution
  493. var includeContent = Effect.IncludesShadersStore[includeFile];
  494. if (match[2]) {
  495. var splits = match[3].split(",");
  496. for (var index = 0; index < splits.length; index += 2) {
  497. var source = new RegExp(splits[index], "g");
  498. var dest = splits[index + 1];
  499. includeContent = includeContent.replace(source, dest);
  500. }
  501. }
  502. if (match[4]) {
  503. var indexString = match[5];
  504. if (indexString.indexOf("..") !== -1) {
  505. var indexSplits = indexString.split("..");
  506. var minIndex = parseInt(indexSplits[0]);
  507. var maxIndex = parseInt(indexSplits[1]);
  508. var sourceIncludeContent = includeContent.slice(0);
  509. includeContent = "";
  510. if (isNaN(maxIndex)) {
  511. maxIndex = this._indexParameters[indexSplits[1]];
  512. }
  513. for (var i = minIndex; i < maxIndex; i++) {
  514. if (!this._engine.supportsUniformBuffers) {
  515. // Ubo replacement
  516. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  517. return p1 + "{X}";
  518. });
  519. }
  520. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  521. }
  522. }
  523. else {
  524. if (!this._engine.supportsUniformBuffers) {
  525. // Ubo replacement
  526. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  527. return p1 + "{X}";
  528. });
  529. }
  530. includeContent = includeContent.replace(/\{X\}/g, indexString);
  531. }
  532. }
  533. // Replace
  534. returnValue = returnValue.replace(match[0], includeContent);
  535. }
  536. else {
  537. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  538. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  539. Effect.IncludesShadersStore[includeFile] = fileContent;
  540. _this._processIncludes(returnValue, callback);
  541. });
  542. return;
  543. }
  544. match = regex.exec(sourceCode);
  545. }
  546. callback(returnValue);
  547. };
  548. Effect.prototype._processPrecision = function (source) {
  549. if (source.indexOf("precision highp float") === -1) {
  550. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  551. source = "precision mediump float;\n" + source;
  552. }
  553. else {
  554. source = "precision highp float;\n" + source;
  555. }
  556. }
  557. else {
  558. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  559. source = source.replace("precision highp float", "precision mediump float");
  560. }
  561. }
  562. return source;
  563. };
  564. /**
  565. * Recompiles the webGL program
  566. * @param vertexSourceCode The source code for the vertex shader.
  567. * @param fragmentSourceCode The source code for the fragment shader.
  568. * @param onCompiled Callback called when completed.
  569. * @param onError Callback called on error.
  570. */
  571. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  572. var _this = this;
  573. this._isReady = false;
  574. this._vertexSourceCodeOverride = vertexSourceCode;
  575. this._fragmentSourceCodeOverride = fragmentSourceCode;
  576. this.onError = function (effect, error) {
  577. if (onError) {
  578. onError(error);
  579. }
  580. };
  581. this.onCompiled = function () {
  582. var scenes = _this.getEngine().scenes;
  583. for (var i = 0; i < scenes.length; i++) {
  584. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  585. }
  586. if (onCompiled) {
  587. onCompiled(_this._program);
  588. }
  589. };
  590. this._fallbacks = null;
  591. this._prepareEffect();
  592. };
  593. /**
  594. * Gets the uniform locations of the the specified variable names
  595. * @param names THe names of the variables to lookup.
  596. * @returns Array of locations in the same order as variable names.
  597. */
  598. Effect.prototype.getSpecificUniformLocations = function (names) {
  599. var engine = this._engine;
  600. return engine.getUniforms(this._program, names);
  601. };
  602. /**
  603. * Prepares the effect
  604. */
  605. Effect.prototype._prepareEffect = function () {
  606. var attributesNames = this._attributesNames;
  607. var defines = this.defines;
  608. var fallbacks = this._fallbacks;
  609. this._valueCache = {};
  610. var previousProgram = this._program;
  611. try {
  612. var engine = this._engine;
  613. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  614. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  615. }
  616. else {
  617. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  618. }
  619. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  620. if (engine.supportsUniformBuffers) {
  621. for (var name in this._uniformBuffersNames) {
  622. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  623. }
  624. }
  625. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  626. this._attributes = engine.getAttributes(this._program, attributesNames);
  627. var index;
  628. for (index = 0; index < this._samplers.length; index++) {
  629. var sampler = this.getUniform(this._samplers[index]);
  630. if (sampler == null) {
  631. this._samplers.splice(index, 1);
  632. index--;
  633. }
  634. }
  635. engine.bindSamplers(this);
  636. this._compilationError = "";
  637. this._isReady = true;
  638. if (this.onCompiled) {
  639. this.onCompiled(this);
  640. }
  641. this.onCompileObservable.notifyObservers(this);
  642. this.onCompileObservable.clear();
  643. // Unbind mesh reference in fallbacks
  644. if (this._fallbacks) {
  645. this._fallbacks.unBindMesh();
  646. }
  647. if (previousProgram) {
  648. this.getEngine()._deleteProgram(previousProgram);
  649. }
  650. }
  651. catch (e) {
  652. this._compilationError = e.message;
  653. // Let's go through fallbacks then
  654. BABYLON.Tools.Error("Unable to compile effect:");
  655. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  656. return " " + uniform;
  657. }));
  658. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  659. return " " + attribute;
  660. }));
  661. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  662. BABYLON.Tools.Error("Error: " + this._compilationError);
  663. if (previousProgram) {
  664. this._program = previousProgram;
  665. this._isReady = true;
  666. if (this.onError) {
  667. this.onError(this, this._compilationError);
  668. }
  669. this.onErrorObservable.notifyObservers(this);
  670. }
  671. if (fallbacks && fallbacks.isMoreFallbacks) {
  672. BABYLON.Tools.Error("Trying next fallback.");
  673. this.defines = fallbacks.reduce(this.defines, this);
  674. this._prepareEffect();
  675. }
  676. else { // Sorry we did everything we can
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. this.onErrorObservable.clear();
  682. // Unbind mesh reference in fallbacks
  683. if (this._fallbacks) {
  684. this._fallbacks.unBindMesh();
  685. }
  686. }
  687. }
  688. };
  689. Object.defineProperty(Effect.prototype, "isSupported", {
  690. /**
  691. * Checks if the effect is supported. (Must be called after compilation)
  692. */
  693. get: function () {
  694. return this._compilationError === "";
  695. },
  696. enumerable: true,
  697. configurable: true
  698. });
  699. /**
  700. * Binds a texture to the engine to be used as output of the shader.
  701. * @param channel Name of the output variable.
  702. * @param texture Texture to bind.
  703. */
  704. Effect.prototype._bindTexture = function (channel, texture) {
  705. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  706. };
  707. /**
  708. * Sets a texture on the engine to be used in the shader.
  709. * @param channel Name of the sampler variable.
  710. * @param texture Texture to set.
  711. */
  712. Effect.prototype.setTexture = function (channel, texture) {
  713. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  714. };
  715. /**
  716. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  717. * @param channel Name of the sampler variable.
  718. * @param texture Texture to set.
  719. */
  720. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  721. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  722. };
  723. /**
  724. * Sets an array of textures on the engine to be used in the shader.
  725. * @param channel Name of the variable.
  726. * @param textures Textures to set.
  727. */
  728. Effect.prototype.setTextureArray = function (channel, textures) {
  729. if (this._samplers.indexOf(channel + "Ex") === -1) {
  730. var initialPos = this._samplers.indexOf(channel);
  731. for (var index = 1; index < textures.length; index++) {
  732. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  733. }
  734. }
  735. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  736. };
  737. /**
  738. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  739. * @param channel Name of the sampler variable.
  740. * @param postProcess Post process to get the input texture from.
  741. */
  742. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  743. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  744. };
  745. /**
  746. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  747. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  748. * @param channel Name of the sampler variable.
  749. * @param postProcess Post process to get the output texture from.
  750. */
  751. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  752. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  753. };
  754. /** @hidden */
  755. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  756. var cache = this._valueCache[uniformName];
  757. var flag = matrix.updateFlag;
  758. if (cache !== undefined && cache === flag) {
  759. return false;
  760. }
  761. this._valueCache[uniformName] = flag;
  762. return true;
  763. };
  764. /** @hidden */
  765. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  766. var cache = this._valueCache[uniformName];
  767. if (!cache) {
  768. cache = [x, y];
  769. this._valueCache[uniformName] = cache;
  770. return true;
  771. }
  772. var changed = false;
  773. if (cache[0] !== x) {
  774. cache[0] = x;
  775. changed = true;
  776. }
  777. if (cache[1] !== y) {
  778. cache[1] = y;
  779. changed = true;
  780. }
  781. return changed;
  782. };
  783. /** @hidden */
  784. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  785. var cache = this._valueCache[uniformName];
  786. if (!cache) {
  787. cache = [x, y, z];
  788. this._valueCache[uniformName] = cache;
  789. return true;
  790. }
  791. var changed = false;
  792. if (cache[0] !== x) {
  793. cache[0] = x;
  794. changed = true;
  795. }
  796. if (cache[1] !== y) {
  797. cache[1] = y;
  798. changed = true;
  799. }
  800. if (cache[2] !== z) {
  801. cache[2] = z;
  802. changed = true;
  803. }
  804. return changed;
  805. };
  806. /** @hidden */
  807. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  808. var cache = this._valueCache[uniformName];
  809. if (!cache) {
  810. cache = [x, y, z, w];
  811. this._valueCache[uniformName] = cache;
  812. return true;
  813. }
  814. var changed = false;
  815. if (cache[0] !== x) {
  816. cache[0] = x;
  817. changed = true;
  818. }
  819. if (cache[1] !== y) {
  820. cache[1] = y;
  821. changed = true;
  822. }
  823. if (cache[2] !== z) {
  824. cache[2] = z;
  825. changed = true;
  826. }
  827. if (cache[3] !== w) {
  828. cache[3] = w;
  829. changed = true;
  830. }
  831. return changed;
  832. };
  833. /**
  834. * Binds a buffer to a uniform.
  835. * @param buffer Buffer to bind.
  836. * @param name Name of the uniform variable to bind to.
  837. */
  838. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  839. var bufferName = this._uniformBuffersNames[name];
  840. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  841. return;
  842. }
  843. Effect._baseCache[bufferName] = buffer;
  844. this._engine.bindUniformBufferBase(buffer, bufferName);
  845. };
  846. /**
  847. * Binds block to a uniform.
  848. * @param blockName Name of the block to bind.
  849. * @param index Index to bind.
  850. */
  851. Effect.prototype.bindUniformBlock = function (blockName, index) {
  852. this._engine.bindUniformBlock(this._program, blockName, index);
  853. };
  854. /**
  855. * Sets an interger value on a uniform variable.
  856. * @param uniformName Name of the variable.
  857. * @param value Value to be set.
  858. * @returns this effect.
  859. */
  860. Effect.prototype.setInt = function (uniformName, value) {
  861. var cache = this._valueCache[uniformName];
  862. if (cache !== undefined && cache === value)
  863. return this;
  864. this._valueCache[uniformName] = value;
  865. this._engine.setInt(this.getUniform(uniformName), value);
  866. return this;
  867. };
  868. /**
  869. * Sets an int array on a uniform variable.
  870. * @param uniformName Name of the variable.
  871. * @param array array to be set.
  872. * @returns this effect.
  873. */
  874. Effect.prototype.setIntArray = function (uniformName, array) {
  875. this._valueCache[uniformName] = null;
  876. this._engine.setIntArray(this.getUniform(uniformName), array);
  877. return this;
  878. };
  879. /**
  880. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  881. * @param uniformName Name of the variable.
  882. * @param array array to be set.
  883. * @returns this effect.
  884. */
  885. Effect.prototype.setIntArray2 = function (uniformName, array) {
  886. this._valueCache[uniformName] = null;
  887. this._engine.setIntArray2(this.getUniform(uniformName), array);
  888. return this;
  889. };
  890. /**
  891. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  892. * @param uniformName Name of the variable.
  893. * @param array array to be set.
  894. * @returns this effect.
  895. */
  896. Effect.prototype.setIntArray3 = function (uniformName, array) {
  897. this._valueCache[uniformName] = null;
  898. this._engine.setIntArray3(this.getUniform(uniformName), array);
  899. return this;
  900. };
  901. /**
  902. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  903. * @param uniformName Name of the variable.
  904. * @param array array to be set.
  905. * @returns this effect.
  906. */
  907. Effect.prototype.setIntArray4 = function (uniformName, array) {
  908. this._valueCache[uniformName] = null;
  909. this._engine.setIntArray4(this.getUniform(uniformName), array);
  910. return this;
  911. };
  912. /**
  913. * Sets an float array on a uniform variable.
  914. * @param uniformName Name of the variable.
  915. * @param array array to be set.
  916. * @returns this effect.
  917. */
  918. Effect.prototype.setFloatArray = function (uniformName, array) {
  919. this._valueCache[uniformName] = null;
  920. this._engine.setFloatArray(this.getUniform(uniformName), array);
  921. return this;
  922. };
  923. /**
  924. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  925. * @param uniformName Name of the variable.
  926. * @param array array to be set.
  927. * @returns this effect.
  928. */
  929. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  930. this._valueCache[uniformName] = null;
  931. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  932. return this;
  933. };
  934. /**
  935. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  936. * @param uniformName Name of the variable.
  937. * @param array array to be set.
  938. * @returns this effect.
  939. */
  940. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  941. this._valueCache[uniformName] = null;
  942. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  943. return this;
  944. };
  945. /**
  946. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  947. * @param uniformName Name of the variable.
  948. * @param array array to be set.
  949. * @returns this effect.
  950. */
  951. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  952. this._valueCache[uniformName] = null;
  953. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  954. return this;
  955. };
  956. /**
  957. * Sets an array on a uniform variable.
  958. * @param uniformName Name of the variable.
  959. * @param array array to be set.
  960. * @returns this effect.
  961. */
  962. Effect.prototype.setArray = function (uniformName, array) {
  963. this._valueCache[uniformName] = null;
  964. this._engine.setArray(this.getUniform(uniformName), array);
  965. return this;
  966. };
  967. /**
  968. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  969. * @param uniformName Name of the variable.
  970. * @param array array to be set.
  971. * @returns this effect.
  972. */
  973. Effect.prototype.setArray2 = function (uniformName, array) {
  974. this._valueCache[uniformName] = null;
  975. this._engine.setArray2(this.getUniform(uniformName), array);
  976. return this;
  977. };
  978. /**
  979. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  980. * @param uniformName Name of the variable.
  981. * @param array array to be set.
  982. * @returns this effect.
  983. */
  984. Effect.prototype.setArray3 = function (uniformName, array) {
  985. this._valueCache[uniformName] = null;
  986. this._engine.setArray3(this.getUniform(uniformName), array);
  987. return this;
  988. };
  989. /**
  990. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  991. * @param uniformName Name of the variable.
  992. * @param array array to be set.
  993. * @returns this effect.
  994. */
  995. Effect.prototype.setArray4 = function (uniformName, array) {
  996. this._valueCache[uniformName] = null;
  997. this._engine.setArray4(this.getUniform(uniformName), array);
  998. return this;
  999. };
  1000. /**
  1001. * Sets matrices on a uniform variable.
  1002. * @param uniformName Name of the variable.
  1003. * @param matrices matrices to be set.
  1004. * @returns this effect.
  1005. */
  1006. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1007. if (!matrices) {
  1008. return this;
  1009. }
  1010. this._valueCache[uniformName] = null;
  1011. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1012. return this;
  1013. };
  1014. /**
  1015. * Sets matrix on a uniform variable.
  1016. * @param uniformName Name of the variable.
  1017. * @param matrix matrix to be set.
  1018. * @returns this effect.
  1019. */
  1020. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1021. if (this._cacheMatrix(uniformName, matrix)) {
  1022. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1023. }
  1024. return this;
  1025. };
  1026. /**
  1027. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1028. * @param uniformName Name of the variable.
  1029. * @param matrix matrix to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1033. this._valueCache[uniformName] = null;
  1034. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1035. return this;
  1036. };
  1037. /**
  1038. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1039. * @param uniformName Name of the variable.
  1040. * @param matrix matrix to be set.
  1041. * @returns this effect.
  1042. */
  1043. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1044. this._valueCache[uniformName] = null;
  1045. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1046. return this;
  1047. };
  1048. /**
  1049. * Sets a float on a uniform variable.
  1050. * @param uniformName Name of the variable.
  1051. * @param value value to be set.
  1052. * @returns this effect.
  1053. */
  1054. Effect.prototype.setFloat = function (uniformName, value) {
  1055. var cache = this._valueCache[uniformName];
  1056. if (cache !== undefined && cache === value)
  1057. return this;
  1058. this._valueCache[uniformName] = value;
  1059. this._engine.setFloat(this.getUniform(uniformName), value);
  1060. return this;
  1061. };
  1062. /**
  1063. * Sets a boolean on a uniform variable.
  1064. * @param uniformName Name of the variable.
  1065. * @param bool value to be set.
  1066. * @returns this effect.
  1067. */
  1068. Effect.prototype.setBool = function (uniformName, bool) {
  1069. var cache = this._valueCache[uniformName];
  1070. if (cache !== undefined && cache === bool)
  1071. return this;
  1072. this._valueCache[uniformName] = bool;
  1073. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets a Vector2 on a uniform variable.
  1078. * @param uniformName Name of the variable.
  1079. * @param vector2 vector2 to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1083. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1084. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1085. }
  1086. return this;
  1087. };
  1088. /**
  1089. * Sets a float2 on a uniform variable.
  1090. * @param uniformName Name of the variable.
  1091. * @param x First float in float2.
  1092. * @param y Second float in float2.
  1093. * @returns this effect.
  1094. */
  1095. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1096. if (this._cacheFloat2(uniformName, x, y)) {
  1097. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1098. }
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets a Vector3 on a uniform variable.
  1103. * @param uniformName Name of the variable.
  1104. * @param vector3 Value to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1108. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1109. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1110. }
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a float3 on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param x First float in float3.
  1117. * @param y Second float in float3.
  1118. * @param z Third float in float3.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1122. if (this._cacheFloat3(uniformName, x, y, z)) {
  1123. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a Vector4 on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param vector4 Value to be set.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1134. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1135. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1136. }
  1137. return this;
  1138. };
  1139. /**
  1140. * Sets a float4 on a uniform variable.
  1141. * @param uniformName Name of the variable.
  1142. * @param x First float in float4.
  1143. * @param y Second float in float4.
  1144. * @param z Third float in float4.
  1145. * @param w Fourth float in float4.
  1146. * @returns this effect.
  1147. */
  1148. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1149. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1150. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1151. }
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a Color3 on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param color3 Value to be set.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setColor3 = function (uniformName, color3) {
  1161. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1162. this._engine.setColor3(this.getUniform(uniformName), color3);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Color4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param color3 Value to be set.
  1170. * @param alpha Alpha value to be set.
  1171. * @returns this effect.
  1172. */
  1173. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1174. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1175. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1176. }
  1177. return this;
  1178. };
  1179. /**
  1180. * Sets a Color4 on a uniform variable
  1181. * @param uniformName defines the name of the variable
  1182. * @param color4 defines the value to be set
  1183. * @returns this effect.
  1184. */
  1185. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1186. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1187. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1188. }
  1189. return this;
  1190. };
  1191. /**
  1192. * Resets the cache of effects.
  1193. */
  1194. Effect.ResetCache = function () {
  1195. Effect._baseCache = {};
  1196. };
  1197. Effect._uniqueIdSeed = 0;
  1198. Effect._baseCache = {};
  1199. /**
  1200. * Store of each shader (The can be looked up using effect.key)
  1201. */
  1202. Effect.ShadersStore = {};
  1203. /**
  1204. * Store of each included file for a shader (The can be looked up using effect.key)
  1205. */
  1206. Effect.IncludesShadersStore = {};
  1207. return Effect;
  1208. }());
  1209. BABYLON.Effect = Effect;
  1210. })(BABYLON || (BABYLON = {}));
  1211. //# sourceMappingURL=babylon.effect.js.map
  1212. //# sourceMappingURL=babylon.types.js.map
  1213. var BABYLON;
  1214. (function (BABYLON) {
  1215. var KeyboardEventTypes = /** @class */ (function () {
  1216. function KeyboardEventTypes() {
  1217. }
  1218. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1219. get: function () {
  1220. return KeyboardEventTypes._KEYDOWN;
  1221. },
  1222. enumerable: true,
  1223. configurable: true
  1224. });
  1225. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1226. get: function () {
  1227. return KeyboardEventTypes._KEYUP;
  1228. },
  1229. enumerable: true,
  1230. configurable: true
  1231. });
  1232. KeyboardEventTypes._KEYDOWN = 0x01;
  1233. KeyboardEventTypes._KEYUP = 0x02;
  1234. return KeyboardEventTypes;
  1235. }());
  1236. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1237. var KeyboardInfo = /** @class */ (function () {
  1238. function KeyboardInfo(type, event) {
  1239. this.type = type;
  1240. this.event = event;
  1241. }
  1242. return KeyboardInfo;
  1243. }());
  1244. BABYLON.KeyboardInfo = KeyboardInfo;
  1245. /**
  1246. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1247. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1248. */
  1249. var KeyboardInfoPre = /** @class */ (function (_super) {
  1250. __extends(KeyboardInfoPre, _super);
  1251. function KeyboardInfoPre(type, event) {
  1252. var _this = _super.call(this, type, event) || this;
  1253. _this.skipOnPointerObservable = false;
  1254. return _this;
  1255. }
  1256. return KeyboardInfoPre;
  1257. }(KeyboardInfo));
  1258. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1259. })(BABYLON || (BABYLON = {}));
  1260. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1261. var BABYLON;
  1262. (function (BABYLON) {
  1263. var PointerEventTypes = /** @class */ (function () {
  1264. function PointerEventTypes() {
  1265. }
  1266. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1267. get: function () {
  1268. return PointerEventTypes._POINTERDOWN;
  1269. },
  1270. enumerable: true,
  1271. configurable: true
  1272. });
  1273. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1274. get: function () {
  1275. return PointerEventTypes._POINTERUP;
  1276. },
  1277. enumerable: true,
  1278. configurable: true
  1279. });
  1280. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1281. get: function () {
  1282. return PointerEventTypes._POINTERMOVE;
  1283. },
  1284. enumerable: true,
  1285. configurable: true
  1286. });
  1287. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1288. get: function () {
  1289. return PointerEventTypes._POINTERWHEEL;
  1290. },
  1291. enumerable: true,
  1292. configurable: true
  1293. });
  1294. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1295. get: function () {
  1296. return PointerEventTypes._POINTERPICK;
  1297. },
  1298. enumerable: true,
  1299. configurable: true
  1300. });
  1301. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1302. get: function () {
  1303. return PointerEventTypes._POINTERTAP;
  1304. },
  1305. enumerable: true,
  1306. configurable: true
  1307. });
  1308. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1309. get: function () {
  1310. return PointerEventTypes._POINTERDOUBLETAP;
  1311. },
  1312. enumerable: true,
  1313. configurable: true
  1314. });
  1315. PointerEventTypes._POINTERDOWN = 0x01;
  1316. PointerEventTypes._POINTERUP = 0x02;
  1317. PointerEventTypes._POINTERMOVE = 0x04;
  1318. PointerEventTypes._POINTERWHEEL = 0x08;
  1319. PointerEventTypes._POINTERPICK = 0x10;
  1320. PointerEventTypes._POINTERTAP = 0x20;
  1321. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1322. return PointerEventTypes;
  1323. }());
  1324. BABYLON.PointerEventTypes = PointerEventTypes;
  1325. var PointerInfoBase = /** @class */ (function () {
  1326. function PointerInfoBase(type, event) {
  1327. this.type = type;
  1328. this.event = event;
  1329. }
  1330. return PointerInfoBase;
  1331. }());
  1332. BABYLON.PointerInfoBase = PointerInfoBase;
  1333. /**
  1334. * This class is used to store pointer related info for the onPrePointerObservable event.
  1335. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1336. */
  1337. var PointerInfoPre = /** @class */ (function (_super) {
  1338. __extends(PointerInfoPre, _super);
  1339. function PointerInfoPre(type, event, localX, localY) {
  1340. var _this = _super.call(this, type, event) || this;
  1341. /**
  1342. * Ray from a pointer if availible (eg. 6dof controller)
  1343. */
  1344. _this.ray = null;
  1345. _this.skipOnPointerObservable = false;
  1346. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1347. return _this;
  1348. }
  1349. return PointerInfoPre;
  1350. }(PointerInfoBase));
  1351. BABYLON.PointerInfoPre = PointerInfoPre;
  1352. /**
  1353. * This type contains all the data related to a pointer event in Babylon.js.
  1354. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1355. */
  1356. var PointerInfo = /** @class */ (function (_super) {
  1357. __extends(PointerInfo, _super);
  1358. function PointerInfo(type, event, pickInfo) {
  1359. var _this = _super.call(this, type, event) || this;
  1360. _this.pickInfo = pickInfo;
  1361. return _this;
  1362. }
  1363. return PointerInfo;
  1364. }(PointerInfoBase));
  1365. BABYLON.PointerInfo = PointerInfo;
  1366. })(BABYLON || (BABYLON = {}));
  1367. //# sourceMappingURL=babylon.pointerEvents.js.map
  1368. var BABYLON;
  1369. (function (BABYLON) {
  1370. BABYLON.ToGammaSpace = 1 / 2.2;
  1371. BABYLON.ToLinearSpace = 2.2;
  1372. BABYLON.Epsilon = 0.001;
  1373. /**
  1374. * Class used to hold a RBG color
  1375. */
  1376. var Color3 = /** @class */ (function () {
  1377. /**
  1378. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1379. * @param r defines the red component (between 0 and 1, default is 0)
  1380. * @param g defines the green component (between 0 and 1, default is 0)
  1381. * @param b defines the blue component (between 0 and 1, default is 0)
  1382. */
  1383. function Color3(
  1384. /**
  1385. * Defines the red component (between 0 and 1, default is 0)
  1386. */
  1387. r,
  1388. /**
  1389. * Defines the green component (between 0 and 1, default is 0)
  1390. */
  1391. g,
  1392. /**
  1393. * Defines the blue component (between 0 and 1, default is 0)
  1394. */
  1395. b) {
  1396. if (r === void 0) { r = 0; }
  1397. if (g === void 0) { g = 0; }
  1398. if (b === void 0) { b = 0; }
  1399. this.r = r;
  1400. this.g = g;
  1401. this.b = b;
  1402. }
  1403. /**
  1404. * Creates a string with the Color3 current values
  1405. * @returns the string representation of the Color3 object
  1406. */
  1407. Color3.prototype.toString = function () {
  1408. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1409. };
  1410. /**
  1411. * Returns the string "Color3"
  1412. * @returns "Color3"
  1413. */
  1414. Color3.prototype.getClassName = function () {
  1415. return "Color3";
  1416. };
  1417. /**
  1418. * Compute the Color3 hash code
  1419. * @returns an unique number that can be used to hash Color3 objects
  1420. */
  1421. Color3.prototype.getHashCode = function () {
  1422. var hash = this.r || 0;
  1423. hash = (hash * 397) ^ (this.g || 0);
  1424. hash = (hash * 397) ^ (this.b || 0);
  1425. return hash;
  1426. };
  1427. // Operators
  1428. /**
  1429. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1430. * @param array defines the array where to store the r,g,b components
  1431. * @param index defines an optional index in the target array to define where to start storing values
  1432. * @returns the current Color3 object
  1433. */
  1434. Color3.prototype.toArray = function (array, index) {
  1435. if (index === undefined) {
  1436. index = 0;
  1437. }
  1438. array[index] = this.r;
  1439. array[index + 1] = this.g;
  1440. array[index + 2] = this.b;
  1441. return this;
  1442. };
  1443. /**
  1444. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1445. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1446. * @returns a new {BABYLON.Color4} object
  1447. */
  1448. Color3.prototype.toColor4 = function (alpha) {
  1449. if (alpha === void 0) { alpha = 1; }
  1450. return new Color4(this.r, this.g, this.b, alpha);
  1451. };
  1452. /**
  1453. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1454. * @returns the new array
  1455. */
  1456. Color3.prototype.asArray = function () {
  1457. var result = new Array();
  1458. this.toArray(result, 0);
  1459. return result;
  1460. };
  1461. /**
  1462. * Returns the luminance value
  1463. * @returns a float value
  1464. */
  1465. Color3.prototype.toLuminance = function () {
  1466. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1467. };
  1468. /**
  1469. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1470. * @param otherColor defines the second operand
  1471. * @returns the new Color3 object
  1472. */
  1473. Color3.prototype.multiply = function (otherColor) {
  1474. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1475. };
  1476. /**
  1477. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1478. * @param otherColor defines the second operand
  1479. * @param result defines the Color3 object where to store the result
  1480. * @returns the current Color3
  1481. */
  1482. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1483. result.r = this.r * otherColor.r;
  1484. result.g = this.g * otherColor.g;
  1485. result.b = this.b * otherColor.b;
  1486. return this;
  1487. };
  1488. /**
  1489. * Determines equality between Color3 objects
  1490. * @param otherColor defines the second operand
  1491. * @returns true if the rgb values are equal to the given ones
  1492. */
  1493. Color3.prototype.equals = function (otherColor) {
  1494. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1495. };
  1496. /**
  1497. * Determines equality between the current Color3 object and a set of r,b,g values
  1498. * @param r defines the red component to check
  1499. * @param g defines the green component to check
  1500. * @param b defines the blue component to check
  1501. * @returns true if the rgb values are equal to the given ones
  1502. */
  1503. Color3.prototype.equalsFloats = function (r, g, b) {
  1504. return this.r === r && this.g === g && this.b === b;
  1505. };
  1506. /**
  1507. * Multiplies in place each rgb value by scale
  1508. * @param scale defines the scaling factor
  1509. * @returns the updated Color3
  1510. */
  1511. Color3.prototype.scale = function (scale) {
  1512. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1513. };
  1514. /**
  1515. * Multiplies the rgb values by scale and stores the result into "result"
  1516. * @param scale defines the scaling factor
  1517. * @param result defines the Color3 object where to store the result
  1518. * @returns the unmodified current Color3
  1519. */
  1520. Color3.prototype.scaleToRef = function (scale, result) {
  1521. result.r = this.r * scale;
  1522. result.g = this.g * scale;
  1523. result.b = this.b * scale;
  1524. return this;
  1525. };
  1526. /**
  1527. * Scale the current Color3 values by a factor and add the result to a given Color3
  1528. * @param scale defines the scale factor
  1529. * @param result defines color to store the result into
  1530. * @returns the unmodified current Color3
  1531. */
  1532. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1533. result.r += this.r * scale;
  1534. result.g += this.g * scale;
  1535. result.b += this.b * scale;
  1536. return this;
  1537. };
  1538. /**
  1539. * Clamps the rgb values by the min and max values and stores the result into "result"
  1540. * @param min defines minimum clamping value (default is 0)
  1541. * @param max defines maximum clamping value (default is 1)
  1542. * @param result defines color to store the result into
  1543. * @returns the original Color3
  1544. */
  1545. Color3.prototype.clampToRef = function (min, max, result) {
  1546. if (min === void 0) { min = 0; }
  1547. if (max === void 0) { max = 1; }
  1548. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1549. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1550. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1551. return this;
  1552. };
  1553. /**
  1554. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1555. * @param otherColor defines the second operand
  1556. * @returns the new Color3
  1557. */
  1558. Color3.prototype.add = function (otherColor) {
  1559. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1560. };
  1561. /**
  1562. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1563. * @param otherColor defines the second operand
  1564. * @param result defines Color3 object to store the result into
  1565. * @returns the unmodified current Color3
  1566. */
  1567. Color3.prototype.addToRef = function (otherColor, result) {
  1568. result.r = this.r + otherColor.r;
  1569. result.g = this.g + otherColor.g;
  1570. result.b = this.b + otherColor.b;
  1571. return this;
  1572. };
  1573. /**
  1574. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1575. * @param otherColor defines the second operand
  1576. * @returns the new Color3
  1577. */
  1578. Color3.prototype.subtract = function (otherColor) {
  1579. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1580. };
  1581. /**
  1582. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1583. * @param otherColor defines the second operand
  1584. * @param result defines Color3 object to store the result into
  1585. * @returns the unmodified current Color3
  1586. */
  1587. Color3.prototype.subtractToRef = function (otherColor, result) {
  1588. result.r = this.r - otherColor.r;
  1589. result.g = this.g - otherColor.g;
  1590. result.b = this.b - otherColor.b;
  1591. return this;
  1592. };
  1593. /**
  1594. * Copy the current object
  1595. * @returns a new Color3 copied the current one
  1596. */
  1597. Color3.prototype.clone = function () {
  1598. return new Color3(this.r, this.g, this.b);
  1599. };
  1600. /**
  1601. * Copies the rgb values from the source in the current Color3
  1602. * @param source defines the source Color3 object
  1603. * @returns the updated Color3 object
  1604. */
  1605. Color3.prototype.copyFrom = function (source) {
  1606. this.r = source.r;
  1607. this.g = source.g;
  1608. this.b = source.b;
  1609. return this;
  1610. };
  1611. /**
  1612. * Updates the Color3 rgb values from the given floats
  1613. * @param r defines the red component to read from
  1614. * @param g defines the green component to read from
  1615. * @param b defines the blue component to read from
  1616. * @returns the current Color3 object
  1617. */
  1618. Color3.prototype.copyFromFloats = function (r, g, b) {
  1619. this.r = r;
  1620. this.g = g;
  1621. this.b = b;
  1622. return this;
  1623. };
  1624. /**
  1625. * Updates the Color3 rgb values from the given floats
  1626. * @param r defines the red component to read from
  1627. * @param g defines the green component to read from
  1628. * @param b defines the blue component to read from
  1629. * @returns the current Color3 object
  1630. */
  1631. Color3.prototype.set = function (r, g, b) {
  1632. return this.copyFromFloats(r, g, b);
  1633. };
  1634. /**
  1635. * Compute the Color3 hexadecimal code as a string
  1636. * @returns a string containing the hexadecimal representation of the Color3 object
  1637. */
  1638. Color3.prototype.toHexString = function () {
  1639. var intR = (this.r * 255) | 0;
  1640. var intG = (this.g * 255) | 0;
  1641. var intB = (this.b * 255) | 0;
  1642. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1643. };
  1644. /**
  1645. * Computes a new Color3 converted from the current one to linear space
  1646. * @returns a new Color3 object
  1647. */
  1648. Color3.prototype.toLinearSpace = function () {
  1649. var convertedColor = new Color3();
  1650. this.toLinearSpaceToRef(convertedColor);
  1651. return convertedColor;
  1652. };
  1653. /**
  1654. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1655. * @param convertedColor defines the Color3 object where to store the linear space version
  1656. * @returns the unmodified Color3
  1657. */
  1658. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1659. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1660. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1661. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1662. return this;
  1663. };
  1664. /**
  1665. * Computes a new Color3 converted from the current one to gamma space
  1666. * @returns a new Color3 object
  1667. */
  1668. Color3.prototype.toGammaSpace = function () {
  1669. var convertedColor = new Color3();
  1670. this.toGammaSpaceToRef(convertedColor);
  1671. return convertedColor;
  1672. };
  1673. /**
  1674. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1675. * @param convertedColor defines the Color3 object where to store the gamma space version
  1676. * @returns the unmodified Color3
  1677. */
  1678. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1679. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1680. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1681. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1682. return this;
  1683. };
  1684. // Statics
  1685. /**
  1686. * Creates a new Color3 from the string containing valid hexadecimal values
  1687. * @param hex defines a string containing valid hexadecimal values
  1688. * @returns a new Color3 object
  1689. */
  1690. Color3.FromHexString = function (hex) {
  1691. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1692. return new Color3(0, 0, 0);
  1693. }
  1694. var r = parseInt(hex.substring(1, 3), 16);
  1695. var g = parseInt(hex.substring(3, 5), 16);
  1696. var b = parseInt(hex.substring(5, 7), 16);
  1697. return Color3.FromInts(r, g, b);
  1698. };
  1699. /**
  1700. * Creates a new Vector3 from the starting index of the given array
  1701. * @param array defines the source array
  1702. * @param offset defines an offset in the source array
  1703. * @returns a new Color3 object
  1704. */
  1705. Color3.FromArray = function (array, offset) {
  1706. if (offset === void 0) { offset = 0; }
  1707. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1708. };
  1709. /**
  1710. * Creates a new Color3 from integer values (< 256)
  1711. * @param r defines the red component to read from (value between 0 and 255)
  1712. * @param g defines the green component to read from (value between 0 and 255)
  1713. * @param b defines the blue component to read from (value between 0 and 255)
  1714. * @returns a new Color3 object
  1715. */
  1716. Color3.FromInts = function (r, g, b) {
  1717. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1718. };
  1719. /**
  1720. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1721. * @param start defines the start Color3 value
  1722. * @param end defines the end Color3 value
  1723. * @param amount defines the gradient value between start and end
  1724. * @returns a new Color3 object
  1725. */
  1726. Color3.Lerp = function (start, end, amount) {
  1727. var r = start.r + ((end.r - start.r) * amount);
  1728. var g = start.g + ((end.g - start.g) * amount);
  1729. var b = start.b + ((end.b - start.b) * amount);
  1730. return new Color3(r, g, b);
  1731. };
  1732. /**
  1733. * Returns a Color3 value containing a red color
  1734. * @returns a new Color3 object
  1735. */
  1736. Color3.Red = function () { return new Color3(1, 0, 0); };
  1737. /**
  1738. * Returns a Color3 value containing a green color
  1739. * @returns a new Color3 object
  1740. */
  1741. Color3.Green = function () { return new Color3(0, 1, 0); };
  1742. /**
  1743. * Returns a Color3 value containing a blue color
  1744. * @returns a new Color3 object
  1745. */
  1746. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1747. /**
  1748. * Returns a Color3 value containing a black color
  1749. * @returns a new Color3 object
  1750. */
  1751. Color3.Black = function () { return new Color3(0, 0, 0); };
  1752. /**
  1753. * Returns a Color3 value containing a white color
  1754. * @returns a new Color3 object
  1755. */
  1756. Color3.White = function () { return new Color3(1, 1, 1); };
  1757. /**
  1758. * Returns a Color3 value containing a purple color
  1759. * @returns a new Color3 object
  1760. */
  1761. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1762. /**
  1763. * Returns a Color3 value containing a magenta color
  1764. * @returns a new Color3 object
  1765. */
  1766. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1767. /**
  1768. * Returns a Color3 value containing a yellow color
  1769. * @returns a new Color3 object
  1770. */
  1771. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1772. /**
  1773. * Returns a Color3 value containing a gray color
  1774. * @returns a new Color3 object
  1775. */
  1776. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1777. /**
  1778. * Returns a Color3 value containing a teal color
  1779. * @returns a new Color3 object
  1780. */
  1781. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1782. /**
  1783. * Returns a Color3 value containing a random color
  1784. * @returns a new Color3 object
  1785. */
  1786. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1787. return Color3;
  1788. }());
  1789. BABYLON.Color3 = Color3;
  1790. /**
  1791. * Class used to hold a RBGA color
  1792. */
  1793. var Color4 = /** @class */ (function () {
  1794. /**
  1795. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1796. * @param r defines the red component (between 0 and 1, default is 0)
  1797. * @param g defines the green component (between 0 and 1, default is 0)
  1798. * @param b defines the blue component (between 0 and 1, default is 0)
  1799. * @param a defines the alpha component (between 0 and 1, default is 1)
  1800. */
  1801. function Color4(
  1802. /**
  1803. * Defines the red component (between 0 and 1, default is 0)
  1804. */
  1805. r,
  1806. /**
  1807. * Defines the green component (between 0 and 1, default is 0)
  1808. */
  1809. g,
  1810. /**
  1811. * Defines the blue component (between 0 and 1, default is 0)
  1812. */
  1813. b,
  1814. /**
  1815. * Defines the alpha component (between 0 and 1, default is 1)
  1816. */
  1817. a) {
  1818. if (r === void 0) { r = 0; }
  1819. if (g === void 0) { g = 0; }
  1820. if (b === void 0) { b = 0; }
  1821. if (a === void 0) { a = 1; }
  1822. this.r = r;
  1823. this.g = g;
  1824. this.b = b;
  1825. this.a = a;
  1826. }
  1827. // Operators
  1828. /**
  1829. * Adds in place the given Color4 values to the current Color4 object
  1830. * @param right defines the second operand
  1831. * @returns the current updated Color4 object
  1832. */
  1833. Color4.prototype.addInPlace = function (right) {
  1834. this.r += right.r;
  1835. this.g += right.g;
  1836. this.b += right.b;
  1837. this.a += right.a;
  1838. return this;
  1839. };
  1840. /**
  1841. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1842. * @returns the new array
  1843. */
  1844. Color4.prototype.asArray = function () {
  1845. var result = new Array();
  1846. this.toArray(result, 0);
  1847. return result;
  1848. };
  1849. /**
  1850. * Stores from the starting index in the given array the Color4 successive values
  1851. * @param array defines the array where to store the r,g,b components
  1852. * @param index defines an optional index in the target array to define where to start storing values
  1853. * @returns the current Color4 object
  1854. */
  1855. Color4.prototype.toArray = function (array, index) {
  1856. if (index === undefined) {
  1857. index = 0;
  1858. }
  1859. array[index] = this.r;
  1860. array[index + 1] = this.g;
  1861. array[index + 2] = this.b;
  1862. array[index + 3] = this.a;
  1863. return this;
  1864. };
  1865. /**
  1866. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1867. * @param right defines the second operand
  1868. * @returns a new Color4 object
  1869. */
  1870. Color4.prototype.add = function (right) {
  1871. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1872. };
  1873. /**
  1874. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1875. * @param right defines the second operand
  1876. * @returns a new Color4 object
  1877. */
  1878. Color4.prototype.subtract = function (right) {
  1879. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1880. };
  1881. /**
  1882. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1883. * @param right defines the second operand
  1884. * @param result defines the Color4 object where to store the result
  1885. * @returns the current Color4 object
  1886. */
  1887. Color4.prototype.subtractToRef = function (right, result) {
  1888. result.r = this.r - right.r;
  1889. result.g = this.g - right.g;
  1890. result.b = this.b - right.b;
  1891. result.a = this.a - right.a;
  1892. return this;
  1893. };
  1894. /**
  1895. * Creates a new Color4 with the current Color4 values multiplied by scale
  1896. * @param scale defines the scaling factor to apply
  1897. * @returns a new Color4 object
  1898. */
  1899. Color4.prototype.scale = function (scale) {
  1900. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1901. };
  1902. /**
  1903. * Multiplies the current Color4 values by scale and stores the result in "result"
  1904. * @param scale defines the scaling factor to apply
  1905. * @param result defines the Color4 object where to store the result
  1906. * @returns the current unmodified Color4
  1907. */
  1908. Color4.prototype.scaleToRef = function (scale, result) {
  1909. result.r = this.r * scale;
  1910. result.g = this.g * scale;
  1911. result.b = this.b * scale;
  1912. result.a = this.a * scale;
  1913. return this;
  1914. };
  1915. /**
  1916. * Scale the current Color4 values by a factor and add the result to a given Color4
  1917. * @param scale defines the scale factor
  1918. * @param result defines the Color4 object where to store the result
  1919. * @returns the unmodified current Color4
  1920. */
  1921. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1922. result.r += this.r * scale;
  1923. result.g += this.g * scale;
  1924. result.b += this.b * scale;
  1925. result.a += this.a * scale;
  1926. return this;
  1927. };
  1928. /**
  1929. * Clamps the rgb values by the min and max values and stores the result into "result"
  1930. * @param min defines minimum clamping value (default is 0)
  1931. * @param max defines maximum clamping value (default is 1)
  1932. * @param result defines color to store the result into.
  1933. * @returns the cuurent Color4
  1934. */
  1935. Color4.prototype.clampToRef = function (min, max, result) {
  1936. if (min === void 0) { min = 0; }
  1937. if (max === void 0) { max = 1; }
  1938. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1939. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1940. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1941. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1942. return this;
  1943. };
  1944. /**
  1945. * Multipy an Color4 value by another and return a new Color4 object
  1946. * @param color defines the Color4 value to multiply by
  1947. * @returns a new Color4 object
  1948. */
  1949. Color4.prototype.multiply = function (color) {
  1950. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1951. };
  1952. /**
  1953. * Multipy a Color4 value by another and push the result in a reference value
  1954. * @param color defines the Color4 value to multiply by
  1955. * @param result defines the Color4 to fill the result in
  1956. * @returns the result Color4
  1957. */
  1958. Color4.prototype.multiplyToRef = function (color, result) {
  1959. result.r = this.r * color.r;
  1960. result.g = this.g * color.g;
  1961. result.b = this.b * color.b;
  1962. result.a = this.a * color.a;
  1963. return result;
  1964. };
  1965. /**
  1966. * Creates a string with the Color4 current values
  1967. * @returns the string representation of the Color4 object
  1968. */
  1969. Color4.prototype.toString = function () {
  1970. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1971. };
  1972. /**
  1973. * Returns the string "Color4"
  1974. * @returns "Color4"
  1975. */
  1976. Color4.prototype.getClassName = function () {
  1977. return "Color4";
  1978. };
  1979. /**
  1980. * Compute the Color4 hash code
  1981. * @returns an unique number that can be used to hash Color4 objects
  1982. */
  1983. Color4.prototype.getHashCode = function () {
  1984. var hash = this.r || 0;
  1985. hash = (hash * 397) ^ (this.g || 0);
  1986. hash = (hash * 397) ^ (this.b || 0);
  1987. hash = (hash * 397) ^ (this.a || 0);
  1988. return hash;
  1989. };
  1990. /**
  1991. * Creates a new Color4 copied from the current one
  1992. * @returns a new Color4 object
  1993. */
  1994. Color4.prototype.clone = function () {
  1995. return new Color4(this.r, this.g, this.b, this.a);
  1996. };
  1997. /**
  1998. * Copies the given Color4 values into the current one
  1999. * @param source defines the source Color4 object
  2000. * @returns the current updated Color4 object
  2001. */
  2002. Color4.prototype.copyFrom = function (source) {
  2003. this.r = source.r;
  2004. this.g = source.g;
  2005. this.b = source.b;
  2006. this.a = source.a;
  2007. return this;
  2008. };
  2009. /**
  2010. * Copies the given float values into the current one
  2011. * @param r defines the red component to read from
  2012. * @param g defines the green component to read from
  2013. * @param b defines the blue component to read from
  2014. * @param a defines the alpha component to read from
  2015. * @returns the current updated Color4 object
  2016. */
  2017. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2018. this.r = r;
  2019. this.g = g;
  2020. this.b = b;
  2021. this.a = a;
  2022. return this;
  2023. };
  2024. /**
  2025. * Copies the given float values into the current one
  2026. * @param r defines the red component to read from
  2027. * @param g defines the green component to read from
  2028. * @param b defines the blue component to read from
  2029. * @param a defines the alpha component to read from
  2030. * @returns the current updated Color4 object
  2031. */
  2032. Color4.prototype.set = function (r, g, b, a) {
  2033. return this.copyFromFloats(r, g, b, a);
  2034. };
  2035. /**
  2036. * Compute the Color4 hexadecimal code as a string
  2037. * @returns a string containing the hexadecimal representation of the Color4 object
  2038. */
  2039. Color4.prototype.toHexString = function () {
  2040. var intR = (this.r * 255) | 0;
  2041. var intG = (this.g * 255) | 0;
  2042. var intB = (this.b * 255) | 0;
  2043. var intA = (this.a * 255) | 0;
  2044. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2045. };
  2046. /**
  2047. * Computes a new Color4 converted from the current one to linear space
  2048. * @returns a new Color4 object
  2049. */
  2050. Color4.prototype.toLinearSpace = function () {
  2051. var convertedColor = new Color4();
  2052. this.toLinearSpaceToRef(convertedColor);
  2053. return convertedColor;
  2054. };
  2055. /**
  2056. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2057. * @param convertedColor defines the Color4 object where to store the linear space version
  2058. * @returns the unmodified Color4
  2059. */
  2060. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2061. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2062. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2063. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2064. convertedColor.a = this.a;
  2065. return this;
  2066. };
  2067. /**
  2068. * Computes a new Color4 converted from the current one to gamma space
  2069. * @returns a new Color4 object
  2070. */
  2071. Color4.prototype.toGammaSpace = function () {
  2072. var convertedColor = new Color4();
  2073. this.toGammaSpaceToRef(convertedColor);
  2074. return convertedColor;
  2075. };
  2076. /**
  2077. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2078. * @param convertedColor defines the Color4 object where to store the gamma space version
  2079. * @returns the unmodified Color4
  2080. */
  2081. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2082. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2083. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2084. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2085. convertedColor.a = this.a;
  2086. return this;
  2087. };
  2088. // Statics
  2089. /**
  2090. * Creates a new Color4 from the string containing valid hexadecimal values
  2091. * @param hex defines a string containing valid hexadecimal values
  2092. * @returns a new Color4 object
  2093. */
  2094. Color4.FromHexString = function (hex) {
  2095. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2096. return new Color4(0.0, 0.0, 0.0, 0.0);
  2097. }
  2098. var r = parseInt(hex.substring(1, 3), 16);
  2099. var g = parseInt(hex.substring(3, 5), 16);
  2100. var b = parseInt(hex.substring(5, 7), 16);
  2101. var a = parseInt(hex.substring(7, 9), 16);
  2102. return Color4.FromInts(r, g, b, a);
  2103. };
  2104. /**
  2105. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2106. * @param left defines the start value
  2107. * @param right defines the end value
  2108. * @param amount defines the gradient factor
  2109. * @returns a new Color4 object
  2110. */
  2111. Color4.Lerp = function (left, right, amount) {
  2112. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2113. Color4.LerpToRef(left, right, amount, result);
  2114. return result;
  2115. };
  2116. /**
  2117. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2118. * @param left defines the start value
  2119. * @param right defines the end value
  2120. * @param amount defines the gradient factor
  2121. * @param result defines the Color4 object where to store data
  2122. */
  2123. Color4.LerpToRef = function (left, right, amount, result) {
  2124. result.r = left.r + (right.r - left.r) * amount;
  2125. result.g = left.g + (right.g - left.g) * amount;
  2126. result.b = left.b + (right.b - left.b) * amount;
  2127. result.a = left.a + (right.a - left.a) * amount;
  2128. };
  2129. /**
  2130. * Creates a new Color4 from the starting index element of the given array
  2131. * @param array defines the source array to read from
  2132. * @param offset defines the offset in the source array
  2133. * @returns a new Color4 object
  2134. */
  2135. Color4.FromArray = function (array, offset) {
  2136. if (offset === void 0) { offset = 0; }
  2137. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2138. };
  2139. /**
  2140. * Creates a new Color3 from integer values (< 256)
  2141. * @param r defines the red component to read from (value between 0 and 255)
  2142. * @param g defines the green component to read from (value between 0 and 255)
  2143. * @param b defines the blue component to read from (value between 0 and 255)
  2144. * @param a defines the alpha component to read from (value between 0 and 255)
  2145. * @returns a new Color3 object
  2146. */
  2147. Color4.FromInts = function (r, g, b, a) {
  2148. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2149. };
  2150. /**
  2151. * Check the content of a given array and convert it to an array containing RGBA data
  2152. * If the original array was already containing count * 4 values then it is returned directly
  2153. * @param colors defines the array to check
  2154. * @param count defines the number of RGBA data to expect
  2155. * @returns an array containing count * 4 values (RGBA)
  2156. */
  2157. Color4.CheckColors4 = function (colors, count) {
  2158. // Check if color3 was used
  2159. if (colors.length === count * 3) {
  2160. var colors4 = [];
  2161. for (var index = 0; index < colors.length; index += 3) {
  2162. var newIndex = (index / 3) * 4;
  2163. colors4[newIndex] = colors[index];
  2164. colors4[newIndex + 1] = colors[index + 1];
  2165. colors4[newIndex + 2] = colors[index + 2];
  2166. colors4[newIndex + 3] = 1.0;
  2167. }
  2168. return colors4;
  2169. }
  2170. return colors;
  2171. };
  2172. return Color4;
  2173. }());
  2174. BABYLON.Color4 = Color4;
  2175. /**
  2176. * Class representing a vector containing 2 coordinates
  2177. */
  2178. var Vector2 = /** @class */ (function () {
  2179. /**
  2180. * Creates a new Vector2 from the given x and y coordinates
  2181. * @param x defines the first coordinate
  2182. * @param y defines the second coordinate
  2183. */
  2184. function Vector2(
  2185. /** defines the first coordinate */
  2186. x,
  2187. /** defines the second coordinate */
  2188. y) {
  2189. this.x = x;
  2190. this.y = y;
  2191. }
  2192. /**
  2193. * Gets a string with the Vector2 coordinates
  2194. * @returns a string with the Vector2 coordinates
  2195. */
  2196. Vector2.prototype.toString = function () {
  2197. return "{X: " + this.x + " Y:" + this.y + "}";
  2198. };
  2199. /**
  2200. * Gets class name
  2201. * @returns the string "Vector2"
  2202. */
  2203. Vector2.prototype.getClassName = function () {
  2204. return "Vector2";
  2205. };
  2206. /**
  2207. * Gets current vector hash code
  2208. * @returns the Vector2 hash code as a number
  2209. */
  2210. Vector2.prototype.getHashCode = function () {
  2211. var hash = this.x || 0;
  2212. hash = (hash * 397) ^ (this.y || 0);
  2213. return hash;
  2214. };
  2215. // Operators
  2216. /**
  2217. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2218. * @param array defines the source array
  2219. * @param index defines the offset in source array
  2220. * @returns the current Vector2
  2221. */
  2222. Vector2.prototype.toArray = function (array, index) {
  2223. if (index === void 0) { index = 0; }
  2224. array[index] = this.x;
  2225. array[index + 1] = this.y;
  2226. return this;
  2227. };
  2228. /**
  2229. * Copy the current vector to an array
  2230. * @returns a new array with 2 elements: the Vector2 coordinates.
  2231. */
  2232. Vector2.prototype.asArray = function () {
  2233. var result = new Array();
  2234. this.toArray(result, 0);
  2235. return result;
  2236. };
  2237. /**
  2238. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2239. * @param source defines the source Vector2
  2240. * @returns the current updated Vector2
  2241. */
  2242. Vector2.prototype.copyFrom = function (source) {
  2243. this.x = source.x;
  2244. this.y = source.y;
  2245. return this;
  2246. };
  2247. /**
  2248. * Sets the Vector2 coordinates with the given floats
  2249. * @param x defines the first coordinate
  2250. * @param y defines the second coordinate
  2251. * @returns the current updated Vector2
  2252. */
  2253. Vector2.prototype.copyFromFloats = function (x, y) {
  2254. this.x = x;
  2255. this.y = y;
  2256. return this;
  2257. };
  2258. /**
  2259. * Sets the Vector2 coordinates with the given floats
  2260. * @param x defines the first coordinate
  2261. * @param y defines the second coordinate
  2262. * @returns the current updated Vector2
  2263. */
  2264. Vector2.prototype.set = function (x, y) {
  2265. return this.copyFromFloats(x, y);
  2266. };
  2267. /**
  2268. * Add another vector with the current one
  2269. * @param otherVector defines the other vector
  2270. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2271. */
  2272. Vector2.prototype.add = function (otherVector) {
  2273. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2274. };
  2275. /**
  2276. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2277. * @param otherVector defines the other vector
  2278. * @param result defines the target vector
  2279. * @returns the unmodified current Vector2
  2280. */
  2281. Vector2.prototype.addToRef = function (otherVector, result) {
  2282. result.x = this.x + otherVector.x;
  2283. result.y = this.y + otherVector.y;
  2284. return this;
  2285. };
  2286. /**
  2287. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2288. * @param otherVector defines the other vector
  2289. * @returns the current updated Vector2
  2290. */
  2291. Vector2.prototype.addInPlace = function (otherVector) {
  2292. this.x += otherVector.x;
  2293. this.y += otherVector.y;
  2294. return this;
  2295. };
  2296. /**
  2297. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2298. * @param otherVector defines the other vector
  2299. * @returns a new Vector2
  2300. */
  2301. Vector2.prototype.addVector3 = function (otherVector) {
  2302. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2303. };
  2304. /**
  2305. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2306. * @param otherVector defines the other vector
  2307. * @returns a new Vector2
  2308. */
  2309. Vector2.prototype.subtract = function (otherVector) {
  2310. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2311. };
  2312. /**
  2313. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2314. * @param otherVector defines the other vector
  2315. * @param result defines the target vector
  2316. * @returns the unmodified current Vector2
  2317. */
  2318. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2319. result.x = this.x - otherVector.x;
  2320. result.y = this.y - otherVector.y;
  2321. return this;
  2322. };
  2323. /**
  2324. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2325. * @param otherVector defines the other vector
  2326. * @returns the current updated Vector2
  2327. */
  2328. Vector2.prototype.subtractInPlace = function (otherVector) {
  2329. this.x -= otherVector.x;
  2330. this.y -= otherVector.y;
  2331. return this;
  2332. };
  2333. /**
  2334. * Multiplies in place the current Vector2 coordinates by the given ones
  2335. * @param otherVector defines the other vector
  2336. * @returns the current updated Vector2
  2337. */
  2338. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2339. this.x *= otherVector.x;
  2340. this.y *= otherVector.y;
  2341. return this;
  2342. };
  2343. /**
  2344. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2345. * @param otherVector defines the other vector
  2346. * @returns a new Vector2
  2347. */
  2348. Vector2.prototype.multiply = function (otherVector) {
  2349. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2350. };
  2351. /**
  2352. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2353. * @param otherVector defines the other vector
  2354. * @param result defines the target vector
  2355. * @returns the unmodified current Vector2
  2356. */
  2357. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2358. result.x = this.x * otherVector.x;
  2359. result.y = this.y * otherVector.y;
  2360. return this;
  2361. };
  2362. /**
  2363. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2364. * @param x defines the first coordinate
  2365. * @param y defines the second coordinate
  2366. * @returns a new Vector2
  2367. */
  2368. Vector2.prototype.multiplyByFloats = function (x, y) {
  2369. return new Vector2(this.x * x, this.y * y);
  2370. };
  2371. /**
  2372. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2373. * @param otherVector defines the other vector
  2374. * @returns a new Vector2
  2375. */
  2376. Vector2.prototype.divide = function (otherVector) {
  2377. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2378. };
  2379. /**
  2380. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2381. * @param otherVector defines the other vector
  2382. * @param result defines the target vector
  2383. * @returns the unmodified current Vector2
  2384. */
  2385. Vector2.prototype.divideToRef = function (otherVector, result) {
  2386. result.x = this.x / otherVector.x;
  2387. result.y = this.y / otherVector.y;
  2388. return this;
  2389. };
  2390. /**
  2391. * Divides the current Vector3 coordinates by the given ones
  2392. * @param otherVector defines the other vector
  2393. * @returns the current updated Vector2
  2394. */
  2395. Vector2.prototype.divideInPlace = function (otherVector) {
  2396. return this.divideToRef(otherVector, this);
  2397. };
  2398. /**
  2399. * Gets a new Vector2 with current Vector2 negated coordinates
  2400. * @returns a new Vector2
  2401. */
  2402. Vector2.prototype.negate = function () {
  2403. return new Vector2(-this.x, -this.y);
  2404. };
  2405. /**
  2406. * Multiply the Vector2 coordinates by scale
  2407. * @param scale defines the scaling factor
  2408. * @returns the current updated Vector2
  2409. */
  2410. Vector2.prototype.scaleInPlace = function (scale) {
  2411. this.x *= scale;
  2412. this.y *= scale;
  2413. return this;
  2414. };
  2415. /**
  2416. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2417. * @param scale defines the scaling factor
  2418. * @returns a new Vector2
  2419. */
  2420. Vector2.prototype.scale = function (scale) {
  2421. var result = new Vector2(0, 0);
  2422. this.scaleToRef(scale, result);
  2423. return result;
  2424. };
  2425. /**
  2426. * Scale the current Vector2 values by a factor to a given Vector2
  2427. * @param scale defines the scale factor
  2428. * @param result defines the Vector2 object where to store the result
  2429. * @returns the unmodified current Vector2
  2430. */
  2431. Vector2.prototype.scaleToRef = function (scale, result) {
  2432. result.x = this.x * scale;
  2433. result.y = this.y * scale;
  2434. return this;
  2435. };
  2436. /**
  2437. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2438. * @param scale defines the scale factor
  2439. * @param result defines the Vector2 object where to store the result
  2440. * @returns the unmodified current Vector2
  2441. */
  2442. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2443. result.x += this.x * scale;
  2444. result.y += this.y * scale;
  2445. return this;
  2446. };
  2447. /**
  2448. * Gets a boolean if two vectors are equals
  2449. * @param otherVector defines the other vector
  2450. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2451. */
  2452. Vector2.prototype.equals = function (otherVector) {
  2453. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2454. };
  2455. /**
  2456. * Gets a boolean if two vectors are equals (using an epsilon value)
  2457. * @param otherVector defines the other vector
  2458. * @param epsilon defines the minimal distance to consider equality
  2459. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2460. */
  2461. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2462. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2463. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2464. };
  2465. // Properties
  2466. /**
  2467. * Gets the length of the vector
  2468. * @returns the vector length (float)
  2469. */
  2470. Vector2.prototype.length = function () {
  2471. return Math.sqrt(this.x * this.x + this.y * this.y);
  2472. };
  2473. /**
  2474. * Gets the vector squared length
  2475. * @returns the vector squared length (float)
  2476. */
  2477. Vector2.prototype.lengthSquared = function () {
  2478. return (this.x * this.x + this.y * this.y);
  2479. };
  2480. // Methods
  2481. /**
  2482. * Normalize the vector
  2483. * @returns the current updated Vector2
  2484. */
  2485. Vector2.prototype.normalize = function () {
  2486. var len = this.length();
  2487. if (len === 0)
  2488. return this;
  2489. var num = 1.0 / len;
  2490. this.x *= num;
  2491. this.y *= num;
  2492. return this;
  2493. };
  2494. /**
  2495. * Gets a new Vector2 copied from the Vector2
  2496. * @returns a new Vector2
  2497. */
  2498. Vector2.prototype.clone = function () {
  2499. return new Vector2(this.x, this.y);
  2500. };
  2501. // Statics
  2502. /**
  2503. * Gets a new Vector2(0, 0)
  2504. * @returns a new Vector2
  2505. */
  2506. Vector2.Zero = function () {
  2507. return new Vector2(0, 0);
  2508. };
  2509. /**
  2510. * Gets a new Vector2(1, 1)
  2511. * @returns a new Vector2
  2512. */
  2513. Vector2.One = function () {
  2514. return new Vector2(1, 1);
  2515. };
  2516. /**
  2517. * Gets a new Vector2 set from the given index element of the given array
  2518. * @param array defines the data source
  2519. * @param offset defines the offset in the data source
  2520. * @returns a new Vector2
  2521. */
  2522. Vector2.FromArray = function (array, offset) {
  2523. if (offset === void 0) { offset = 0; }
  2524. return new Vector2(array[offset], array[offset + 1]);
  2525. };
  2526. /**
  2527. * Sets "result" from the given index element of the given array
  2528. * @param array defines the data source
  2529. * @param offset defines the offset in the data source
  2530. * @param result defines the target vector
  2531. */
  2532. Vector2.FromArrayToRef = function (array, offset, result) {
  2533. result.x = array[offset];
  2534. result.y = array[offset + 1];
  2535. };
  2536. /**
  2537. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2538. * @param value1 defines 1st point of control
  2539. * @param value2 defines 2nd point of control
  2540. * @param value3 defines 3rd point of control
  2541. * @param value4 defines 4th point of control
  2542. * @param amount defines the interpolation factor
  2543. * @returns a new Vector2
  2544. */
  2545. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2546. var squared = amount * amount;
  2547. var cubed = amount * squared;
  2548. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2549. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2550. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2551. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2552. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2553. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2554. return new Vector2(x, y);
  2555. };
  2556. /**
  2557. * 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".
  2558. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2559. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2560. * @param value defines the value to clamp
  2561. * @param min defines the lower limit
  2562. * @param max defines the upper limit
  2563. * @returns a new Vector2
  2564. */
  2565. Vector2.Clamp = function (value, min, max) {
  2566. var x = value.x;
  2567. x = (x > max.x) ? max.x : x;
  2568. x = (x < min.x) ? min.x : x;
  2569. var y = value.y;
  2570. y = (y > max.y) ? max.y : y;
  2571. y = (y < min.y) ? min.y : y;
  2572. return new Vector2(x, y);
  2573. };
  2574. /**
  2575. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2576. * @param value1 defines the 1st control point
  2577. * @param tangent1 defines the outgoing tangent
  2578. * @param value2 defines the 2nd control point
  2579. * @param tangent2 defines the incoming tangent
  2580. * @param amount defines the interpolation factor
  2581. * @returns a new Vector2
  2582. */
  2583. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2584. var squared = amount * amount;
  2585. var cubed = amount * squared;
  2586. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2587. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2588. var part3 = (cubed - (2.0 * squared)) + amount;
  2589. var part4 = cubed - squared;
  2590. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2591. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2592. return new Vector2(x, y);
  2593. };
  2594. /**
  2595. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2596. * @param start defines the start vector
  2597. * @param end defines the end vector
  2598. * @param amount defines the interpolation factor
  2599. * @returns a new Vector2
  2600. */
  2601. Vector2.Lerp = function (start, end, amount) {
  2602. var x = start.x + ((end.x - start.x) * amount);
  2603. var y = start.y + ((end.y - start.y) * amount);
  2604. return new Vector2(x, y);
  2605. };
  2606. /**
  2607. * Gets the dot product of the vector "left" and the vector "right"
  2608. * @param left defines first vector
  2609. * @param right defines second vector
  2610. * @returns the dot product (float)
  2611. */
  2612. Vector2.Dot = function (left, right) {
  2613. return left.x * right.x + left.y * right.y;
  2614. };
  2615. /**
  2616. * Returns a new Vector2 equal to the normalized given vector
  2617. * @param vector defines the vector to normalize
  2618. * @returns a new Vector2
  2619. */
  2620. Vector2.Normalize = function (vector) {
  2621. var newVector = vector.clone();
  2622. newVector.normalize();
  2623. return newVector;
  2624. };
  2625. /**
  2626. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2627. * @param left defines 1st vector
  2628. * @param right defines 2nd vector
  2629. * @returns a new Vector2
  2630. */
  2631. Vector2.Minimize = function (left, right) {
  2632. var x = (left.x < right.x) ? left.x : right.x;
  2633. var y = (left.y < right.y) ? left.y : right.y;
  2634. return new Vector2(x, y);
  2635. };
  2636. /**
  2637. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2638. * @param left defines 1st vector
  2639. * @param right defines 2nd vector
  2640. * @returns a new Vector2
  2641. */
  2642. Vector2.Maximize = function (left, right) {
  2643. var x = (left.x > right.x) ? left.x : right.x;
  2644. var y = (left.y > right.y) ? left.y : right.y;
  2645. return new Vector2(x, y);
  2646. };
  2647. /**
  2648. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2649. * @param vector defines the vector to transform
  2650. * @param transformation defines the matrix to apply
  2651. * @returns a new Vector2
  2652. */
  2653. Vector2.Transform = function (vector, transformation) {
  2654. var r = Vector2.Zero();
  2655. Vector2.TransformToRef(vector, transformation, r);
  2656. return r;
  2657. };
  2658. /**
  2659. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2660. * @param vector defines the vector to transform
  2661. * @param transformation defines the matrix to apply
  2662. * @param result defines the target vector
  2663. */
  2664. Vector2.TransformToRef = function (vector, transformation, result) {
  2665. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2666. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2667. result.x = x;
  2668. result.y = y;
  2669. };
  2670. /**
  2671. * Determines if a given vector is included in a triangle
  2672. * @param p defines the vector to test
  2673. * @param p0 defines 1st triangle point
  2674. * @param p1 defines 2nd triangle point
  2675. * @param p2 defines 3rd triangle point
  2676. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2677. */
  2678. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2679. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2680. var sign = a < 0 ? -1 : 1;
  2681. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2682. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2683. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2684. };
  2685. /**
  2686. * Gets the distance between the vectors "value1" and "value2"
  2687. * @param value1 defines first vector
  2688. * @param value2 defines second vector
  2689. * @returns the distance between vectors
  2690. */
  2691. Vector2.Distance = function (value1, value2) {
  2692. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2693. };
  2694. /**
  2695. * Returns the squared distance between the vectors "value1" and "value2"
  2696. * @param value1 defines first vector
  2697. * @param value2 defines second vector
  2698. * @returns the squared distance between vectors
  2699. */
  2700. Vector2.DistanceSquared = function (value1, value2) {
  2701. var x = value1.x - value2.x;
  2702. var y = value1.y - value2.y;
  2703. return (x * x) + (y * y);
  2704. };
  2705. /**
  2706. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2707. * @param value1 defines first vector
  2708. * @param value2 defines second vector
  2709. * @returns a new Vector2
  2710. */
  2711. Vector2.Center = function (value1, value2) {
  2712. var center = value1.add(value2);
  2713. center.scaleInPlace(0.5);
  2714. return center;
  2715. };
  2716. /**
  2717. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2718. * @param p defines the middle point
  2719. * @param segA defines one point of the segment
  2720. * @param segB defines the other point of the segment
  2721. * @returns the shortest distance
  2722. */
  2723. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2724. var l2 = Vector2.DistanceSquared(segA, segB);
  2725. if (l2 === 0.0) {
  2726. return Vector2.Distance(p, segA);
  2727. }
  2728. var v = segB.subtract(segA);
  2729. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2730. var proj = segA.add(v.multiplyByFloats(t, t));
  2731. return Vector2.Distance(p, proj);
  2732. };
  2733. return Vector2;
  2734. }());
  2735. BABYLON.Vector2 = Vector2;
  2736. /**
  2737. * Classed used to store (x,y,z) vector representation
  2738. * A Vector3 is the main object used in 3D geometry
  2739. * It can represent etiher the coordinates of a point the space, either a direction
  2740. * Reminder: Babylon.js uses a left handed forward facing system
  2741. */
  2742. var Vector3 = /** @class */ (function () {
  2743. /**
  2744. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2745. * @param x defines the first coordinates (on X axis)
  2746. * @param y defines the second coordinates (on Y axis)
  2747. * @param z defines the third coordinates (on Z axis)
  2748. */
  2749. function Vector3(
  2750. /**
  2751. * Defines the first coordinates (on X axis)
  2752. */
  2753. x,
  2754. /**
  2755. * Defines the second coordinates (on Y axis)
  2756. */
  2757. y,
  2758. /**
  2759. * Defines the third coordinates (on Z axis)
  2760. */
  2761. z) {
  2762. this.x = x;
  2763. this.y = y;
  2764. this.z = z;
  2765. }
  2766. /**
  2767. * Creates a string representation of the Vector3
  2768. * @returns a string with the Vector3 coordinates.
  2769. */
  2770. Vector3.prototype.toString = function () {
  2771. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2772. };
  2773. /**
  2774. * Gets the class name
  2775. * @returns the string "Vector3"
  2776. */
  2777. Vector3.prototype.getClassName = function () {
  2778. return "Vector3";
  2779. };
  2780. /**
  2781. * Creates the Vector3 hash code
  2782. * @returns a number which tends to be unique between Vector3 instances
  2783. */
  2784. Vector3.prototype.getHashCode = function () {
  2785. var hash = this.x || 0;
  2786. hash = (hash * 397) ^ (this.y || 0);
  2787. hash = (hash * 397) ^ (this.z || 0);
  2788. return hash;
  2789. };
  2790. // Operators
  2791. /**
  2792. * Creates an array containing three elements : the coordinates of the Vector3
  2793. * @returns a new array of numbers
  2794. */
  2795. Vector3.prototype.asArray = function () {
  2796. var result = [];
  2797. this.toArray(result, 0);
  2798. return result;
  2799. };
  2800. /**
  2801. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2802. * @param array defines the destination array
  2803. * @param index defines the offset in the destination array
  2804. * @returns the current Vector3
  2805. */
  2806. Vector3.prototype.toArray = function (array, index) {
  2807. if (index === void 0) { index = 0; }
  2808. array[index] = this.x;
  2809. array[index + 1] = this.y;
  2810. array[index + 2] = this.z;
  2811. return this;
  2812. };
  2813. /**
  2814. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2815. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2816. */
  2817. Vector3.prototype.toQuaternion = function () {
  2818. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2819. };
  2820. /**
  2821. * Adds the given vector to the current Vector3
  2822. * @param otherVector defines the second operand
  2823. * @returns the current updated Vector3
  2824. */
  2825. Vector3.prototype.addInPlace = function (otherVector) {
  2826. this.x += otherVector.x;
  2827. this.y += otherVector.y;
  2828. this.z += otherVector.z;
  2829. return this;
  2830. };
  2831. /**
  2832. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2833. * @param otherVector defines the second operand
  2834. * @returns the resulting Vector3
  2835. */
  2836. Vector3.prototype.add = function (otherVector) {
  2837. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2838. };
  2839. /**
  2840. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2841. * @param otherVector defines the second operand
  2842. * @param result defines the Vector3 object where to store the result
  2843. * @returns the current Vector3
  2844. */
  2845. Vector3.prototype.addToRef = function (otherVector, result) {
  2846. result.x = this.x + otherVector.x;
  2847. result.y = this.y + otherVector.y;
  2848. result.z = this.z + otherVector.z;
  2849. return this;
  2850. };
  2851. /**
  2852. * Subtract the given vector from the current Vector3
  2853. * @param otherVector defines the second operand
  2854. * @returns the current updated Vector3
  2855. */
  2856. Vector3.prototype.subtractInPlace = function (otherVector) {
  2857. this.x -= otherVector.x;
  2858. this.y -= otherVector.y;
  2859. this.z -= otherVector.z;
  2860. return this;
  2861. };
  2862. /**
  2863. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2864. * @param otherVector defines the second operand
  2865. * @returns the resulting Vector3
  2866. */
  2867. Vector3.prototype.subtract = function (otherVector) {
  2868. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2869. };
  2870. /**
  2871. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2872. * @param otherVector defines the second operand
  2873. * @param result defines the Vector3 object where to store the result
  2874. * @returns the current Vector3
  2875. */
  2876. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2877. result.x = this.x - otherVector.x;
  2878. result.y = this.y - otherVector.y;
  2879. result.z = this.z - otherVector.z;
  2880. return this;
  2881. };
  2882. /**
  2883. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2884. * @param x defines the x coordinate of the operand
  2885. * @param y defines the y coordinate of the operand
  2886. * @param z defines the z coordinate of the operand
  2887. * @returns the resulting Vector3
  2888. */
  2889. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2890. return new Vector3(this.x - x, this.y - y, this.z - z);
  2891. };
  2892. /**
  2893. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2894. * @param x defines the x coordinate of the operand
  2895. * @param y defines the y coordinate of the operand
  2896. * @param z defines the z coordinate of the operand
  2897. * @param result defines the Vector3 object where to store the result
  2898. * @returns the current Vector3
  2899. */
  2900. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2901. result.x = this.x - x;
  2902. result.y = this.y - y;
  2903. result.z = this.z - z;
  2904. return this;
  2905. };
  2906. /**
  2907. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2908. * @returns a new Vector3
  2909. */
  2910. Vector3.prototype.negate = function () {
  2911. return new Vector3(-this.x, -this.y, -this.z);
  2912. };
  2913. /**
  2914. * Multiplies the Vector3 coordinates by the float "scale"
  2915. * @param scale defines the multiplier factor
  2916. * @returns the current updated Vector3
  2917. */
  2918. Vector3.prototype.scaleInPlace = function (scale) {
  2919. this.x *= scale;
  2920. this.y *= scale;
  2921. this.z *= scale;
  2922. return this;
  2923. };
  2924. /**
  2925. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2926. * @param scale defines the multiplier factor
  2927. * @returns a new Vector3
  2928. */
  2929. Vector3.prototype.scale = function (scale) {
  2930. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2931. };
  2932. /**
  2933. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2934. * @param scale defines the multiplier factor
  2935. * @param result defines the Vector3 object where to store the result
  2936. * @returns the current Vector3
  2937. */
  2938. Vector3.prototype.scaleToRef = function (scale, result) {
  2939. result.x = this.x * scale;
  2940. result.y = this.y * scale;
  2941. result.z = this.z * scale;
  2942. return this;
  2943. };
  2944. /**
  2945. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2946. * @param scale defines the scale factor
  2947. * @param result defines the Vector3 object where to store the result
  2948. * @returns the unmodified current Vector3
  2949. */
  2950. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2951. result.x += this.x * scale;
  2952. result.y += this.y * scale;
  2953. result.z += this.z * scale;
  2954. return this;
  2955. };
  2956. /**
  2957. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2958. * @param otherVector defines the second operand
  2959. * @returns true if both vectors are equals
  2960. */
  2961. Vector3.prototype.equals = function (otherVector) {
  2962. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2963. };
  2964. /**
  2965. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2966. * @param otherVector defines the second operand
  2967. * @param epsilon defines the minimal distance to define values as equals
  2968. * @returns true if both vectors are distant less than epsilon
  2969. */
  2970. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2971. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2972. 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);
  2973. };
  2974. /**
  2975. * Returns true if the current Vector3 coordinates equals the given floats
  2976. * @param x defines the x coordinate of the operand
  2977. * @param y defines the y coordinate of the operand
  2978. * @param z defines the z coordinate of the operand
  2979. * @returns true if both vectors are equals
  2980. */
  2981. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2982. return this.x === x && this.y === y && this.z === z;
  2983. };
  2984. /**
  2985. * Multiplies the current Vector3 coordinates by the given ones
  2986. * @param otherVector defines the second operand
  2987. * @returns the current updated Vector3
  2988. */
  2989. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2990. this.x *= otherVector.x;
  2991. this.y *= otherVector.y;
  2992. this.z *= otherVector.z;
  2993. return this;
  2994. };
  2995. /**
  2996. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  2997. * @param otherVector defines the second operand
  2998. * @returns the new Vector3
  2999. */
  3000. Vector3.prototype.multiply = function (otherVector) {
  3001. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3002. };
  3003. /**
  3004. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3005. * @param otherVector defines the second operand
  3006. * @param result defines the Vector3 object where to store the result
  3007. * @returns the current Vector3
  3008. */
  3009. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3010. result.x = this.x * otherVector.x;
  3011. result.y = this.y * otherVector.y;
  3012. result.z = this.z * otherVector.z;
  3013. return this;
  3014. };
  3015. /**
  3016. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3017. * @param x defines the x coordinate of the operand
  3018. * @param y defines the y coordinate of the operand
  3019. * @param z defines the z coordinate of the operand
  3020. * @returns the new Vector3
  3021. */
  3022. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3023. return new Vector3(this.x * x, this.y * y, this.z * z);
  3024. };
  3025. /**
  3026. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3027. * @param otherVector defines the second operand
  3028. * @returns the new Vector3
  3029. */
  3030. Vector3.prototype.divide = function (otherVector) {
  3031. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3032. };
  3033. /**
  3034. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3035. * @param otherVector defines the second operand
  3036. * @param result defines the Vector3 object where to store the result
  3037. * @returns the current Vector3
  3038. */
  3039. Vector3.prototype.divideToRef = function (otherVector, result) {
  3040. result.x = this.x / otherVector.x;
  3041. result.y = this.y / otherVector.y;
  3042. result.z = this.z / otherVector.z;
  3043. return this;
  3044. };
  3045. /**
  3046. * Divides the current Vector3 coordinates by the given ones.
  3047. * @param otherVector defines the second operand
  3048. * @returns the current updated Vector3
  3049. */
  3050. Vector3.prototype.divideInPlace = function (otherVector) {
  3051. return this.divideToRef(otherVector, this);
  3052. };
  3053. /**
  3054. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3055. * @param other defines the second operand
  3056. * @returns the current updated Vector3
  3057. */
  3058. Vector3.prototype.minimizeInPlace = function (other) {
  3059. if (other.x < this.x)
  3060. this.x = other.x;
  3061. if (other.y < this.y)
  3062. this.y = other.y;
  3063. if (other.z < this.z)
  3064. this.z = other.z;
  3065. return this;
  3066. };
  3067. /**
  3068. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3069. * @param other defines the second operand
  3070. * @returns the current updated Vector3
  3071. */
  3072. Vector3.prototype.maximizeInPlace = function (other) {
  3073. if (other.x > this.x)
  3074. this.x = other.x;
  3075. if (other.y > this.y)
  3076. this.y = other.y;
  3077. if (other.z > this.z)
  3078. this.z = other.z;
  3079. return this;
  3080. };
  3081. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3082. /**
  3083. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3084. */
  3085. get: function () {
  3086. var absX = Math.abs(this.x);
  3087. var absY = Math.abs(this.y);
  3088. if (absX !== absY) {
  3089. return true;
  3090. }
  3091. var absZ = Math.abs(this.z);
  3092. if (absX !== absZ) {
  3093. return true;
  3094. }
  3095. if (absY !== absZ) {
  3096. return true;
  3097. }
  3098. return false;
  3099. },
  3100. enumerable: true,
  3101. configurable: true
  3102. });
  3103. // Properties
  3104. /**
  3105. * Gets the length of the Vector3
  3106. * @returns the length of the Vecto3
  3107. */
  3108. Vector3.prototype.length = function () {
  3109. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3110. };
  3111. /**
  3112. * Gets the squared length of the Vector3
  3113. * @returns squared length of the Vector3
  3114. */
  3115. Vector3.prototype.lengthSquared = function () {
  3116. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3117. };
  3118. /**
  3119. * Normalize the current Vector3.
  3120. * Please note that this is an in place operation.
  3121. * @returns the current updated Vector3
  3122. */
  3123. Vector3.prototype.normalize = function () {
  3124. var len = this.length();
  3125. if (len === 0 || len === 1.0)
  3126. return this;
  3127. var num = 1.0 / len;
  3128. this.x *= num;
  3129. this.y *= num;
  3130. this.z *= num;
  3131. return this;
  3132. };
  3133. /**
  3134. * Normalize the current Vector3 to a new vector
  3135. * @returns the new Vector3
  3136. */
  3137. Vector3.prototype.normalizeToNew = function () {
  3138. var normalized = new Vector3(0, 0, 0);
  3139. this.normalizeToRef(normalized);
  3140. return normalized;
  3141. };
  3142. /**
  3143. * Normalize the current Vector3 to the reference
  3144. * @param reference define the Vector3 to update
  3145. * @returns the updated Vector3
  3146. */
  3147. Vector3.prototype.normalizeToRef = function (reference) {
  3148. var len = this.length();
  3149. if (len === 0 || len === 1.0) {
  3150. reference.set(this.x, this.y, this.z);
  3151. return reference;
  3152. }
  3153. var scale = 1.0 / len;
  3154. this.scaleToRef(scale, reference);
  3155. return reference;
  3156. };
  3157. /**
  3158. * Creates a new Vector3 copied from the current Vector3
  3159. * @returns the new Vector3
  3160. */
  3161. Vector3.prototype.clone = function () {
  3162. return new Vector3(this.x, this.y, this.z);
  3163. };
  3164. /**
  3165. * Copies the given vector coordinates to the current Vector3 ones
  3166. * @param source defines the source Vector3
  3167. * @returns the current updated Vector3
  3168. */
  3169. Vector3.prototype.copyFrom = function (source) {
  3170. this.x = source.x;
  3171. this.y = source.y;
  3172. this.z = source.z;
  3173. return this;
  3174. };
  3175. /**
  3176. * Copies the given floats to the current Vector3 coordinates
  3177. * @param x defines the x coordinate of the operand
  3178. * @param y defines the y coordinate of the operand
  3179. * @param z defines the z coordinate of the operand
  3180. * @returns the current updated Vector3
  3181. */
  3182. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3183. this.x = x;
  3184. this.y = y;
  3185. this.z = z;
  3186. return this;
  3187. };
  3188. /**
  3189. * Copies the given floats to the current Vector3 coordinates
  3190. * @param x defines the x coordinate of the operand
  3191. * @param y defines the y coordinate of the operand
  3192. * @param z defines the z coordinate of the operand
  3193. * @returns the current updated Vector3
  3194. */
  3195. Vector3.prototype.set = function (x, y, z) {
  3196. return this.copyFromFloats(x, y, z);
  3197. };
  3198. // Statics
  3199. /**
  3200. * Get the clip factor between two vectors
  3201. * @param vector0 defines the first operand
  3202. * @param vector1 defines the second operand
  3203. * @param axis defines the axis to use
  3204. * @param size defines the size along the axis
  3205. * @returns the clip factor
  3206. */
  3207. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3208. var d0 = Vector3.Dot(vector0, axis) - size;
  3209. var d1 = Vector3.Dot(vector1, axis) - size;
  3210. var s = d0 / (d0 - d1);
  3211. return s;
  3212. };
  3213. /**
  3214. * Get angle between two vectors
  3215. * @param vector0 angle between vector0 and vector1
  3216. * @param vector1 angle between vector0 and vector1
  3217. * @param normal direction of the normal
  3218. * @return the angle between vector0 and vector1
  3219. */
  3220. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3221. var v0 = vector0.clone().normalize();
  3222. var v1 = vector1.clone().normalize();
  3223. var dot = Vector3.Dot(v0, v1);
  3224. var n = Vector3.Cross(v0, v1);
  3225. if (Vector3.Dot(n, normal) > 0) {
  3226. return Math.acos(dot);
  3227. }
  3228. return -Math.acos(dot);
  3229. };
  3230. /**
  3231. * Returns a new Vector3 set from the index "offset" of the given array
  3232. * @param array defines the source array
  3233. * @param offset defines the offset in the source array
  3234. * @returns the new Vector3
  3235. */
  3236. Vector3.FromArray = function (array, offset) {
  3237. if (!offset) {
  3238. offset = 0;
  3239. }
  3240. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3241. };
  3242. /**
  3243. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3244. * This function is deprecated. Use FromArray instead
  3245. * @param array defines the source array
  3246. * @param offset defines the offset in the source array
  3247. * @returns the new Vector3
  3248. */
  3249. Vector3.FromFloatArray = function (array, offset) {
  3250. return Vector3.FromArray(array, offset);
  3251. };
  3252. /**
  3253. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3254. * @param array defines the source array
  3255. * @param offset defines the offset in the source array
  3256. * @param result defines the Vector3 where to store the result
  3257. */
  3258. Vector3.FromArrayToRef = function (array, offset, result) {
  3259. result.x = array[offset];
  3260. result.y = array[offset + 1];
  3261. result.z = array[offset + 2];
  3262. };
  3263. /**
  3264. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3265. * This function is deprecated. Use FromArrayToRef instead.
  3266. * @param array defines the source array
  3267. * @param offset defines the offset in the source array
  3268. * @param result defines the Vector3 where to store the result
  3269. */
  3270. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3271. return Vector3.FromArrayToRef(array, offset, result);
  3272. };
  3273. /**
  3274. * Sets the given vector "result" with the given floats.
  3275. * @param x defines the x coordinate of the source
  3276. * @param y defines the y coordinate of the source
  3277. * @param z defines the z coordinate of the source
  3278. * @param result defines the Vector3 where to store the result
  3279. */
  3280. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3281. result.x = x;
  3282. result.y = y;
  3283. result.z = z;
  3284. };
  3285. /**
  3286. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3287. * @returns a new empty Vector3
  3288. */
  3289. Vector3.Zero = function () {
  3290. return new Vector3(0.0, 0.0, 0.0);
  3291. };
  3292. /**
  3293. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3294. * @returns a new unit Vector3
  3295. */
  3296. Vector3.One = function () {
  3297. return new Vector3(1.0, 1.0, 1.0);
  3298. };
  3299. /**
  3300. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3301. * @returns a new up Vector3
  3302. */
  3303. Vector3.Up = function () {
  3304. return new Vector3(0.0, 1.0, 0.0);
  3305. };
  3306. /**
  3307. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3308. * @returns a new down Vector3
  3309. */
  3310. Vector3.Down = function () {
  3311. return new Vector3(0.0, -1.0, 0.0);
  3312. };
  3313. /**
  3314. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3315. * @returns a new forward Vector3
  3316. */
  3317. Vector3.Forward = function () {
  3318. return new Vector3(0.0, 0.0, 1.0);
  3319. };
  3320. /**
  3321. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3322. * @returns a new right Vector3
  3323. */
  3324. Vector3.Right = function () {
  3325. return new Vector3(1.0, 0.0, 0.0);
  3326. };
  3327. /**
  3328. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3329. * @returns a new left Vector3
  3330. */
  3331. Vector3.Left = function () {
  3332. return new Vector3(-1.0, 0.0, 0.0);
  3333. };
  3334. /**
  3335. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3336. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3337. * @param vector defines the Vector3 to transform
  3338. * @param transformation defines the transformation matrix
  3339. * @returns the transformed Vector3
  3340. */
  3341. Vector3.TransformCoordinates = function (vector, transformation) {
  3342. var result = Vector3.Zero();
  3343. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3344. return result;
  3345. };
  3346. /**
  3347. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3348. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3349. * @param vector defines the Vector3 to transform
  3350. * @param transformation defines the transformation matrix
  3351. * @param result defines the Vector3 where to store the result
  3352. */
  3353. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3354. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3355. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3356. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3357. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3358. result.x = x / w;
  3359. result.y = y / w;
  3360. result.z = z / w;
  3361. };
  3362. /**
  3363. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3364. * This method computes tranformed coordinates only, not transformed direction vectors
  3365. * @param x define the x coordinate of the source vector
  3366. * @param y define the y coordinate of the source vector
  3367. * @param z define the z coordinate of the source vector
  3368. * @param transformation defines the transformation matrix
  3369. * @param result defines the Vector3 where to store the result
  3370. */
  3371. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3372. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3373. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3374. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3375. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3376. result.x = rx / rw;
  3377. result.y = ry / rw;
  3378. result.z = rz / rw;
  3379. };
  3380. /**
  3381. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3382. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3383. * @param vector defines the Vector3 to transform
  3384. * @param transformation defines the transformation matrix
  3385. * @returns the new Vector3
  3386. */
  3387. Vector3.TransformNormal = function (vector, transformation) {
  3388. var result = Vector3.Zero();
  3389. Vector3.TransformNormalToRef(vector, transformation, result);
  3390. return result;
  3391. };
  3392. /**
  3393. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3394. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3395. * @param vector defines the Vector3 to transform
  3396. * @param transformation defines the transformation matrix
  3397. * @param result defines the Vector3 where to store the result
  3398. */
  3399. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3400. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3401. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3402. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3403. result.x = x;
  3404. result.y = y;
  3405. result.z = z;
  3406. };
  3407. /**
  3408. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3409. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3410. * @param x define the x coordinate of the source vector
  3411. * @param y define the y coordinate of the source vector
  3412. * @param z define the z coordinate of the source vector
  3413. * @param transformation defines the transformation matrix
  3414. * @param result defines the Vector3 where to store the result
  3415. */
  3416. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3417. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3418. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3419. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3420. };
  3421. /**
  3422. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3423. * @param value1 defines the first control point
  3424. * @param value2 defines the second control point
  3425. * @param value3 defines the third control point
  3426. * @param value4 defines the fourth control point
  3427. * @param amount defines the amount on the spline to use
  3428. * @returns the new Vector3
  3429. */
  3430. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3431. var squared = amount * amount;
  3432. var cubed = amount * squared;
  3433. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3434. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3435. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3436. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3437. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3438. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3439. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3440. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3441. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3442. return new Vector3(x, y, z);
  3443. };
  3444. /**
  3445. * 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"
  3446. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3447. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3448. * @param value defines the current value
  3449. * @param min defines the lower range value
  3450. * @param max defines the upper range value
  3451. * @returns the new Vector3
  3452. */
  3453. Vector3.Clamp = function (value, min, max) {
  3454. var x = value.x;
  3455. x = (x > max.x) ? max.x : x;
  3456. x = (x < min.x) ? min.x : x;
  3457. var y = value.y;
  3458. y = (y > max.y) ? max.y : y;
  3459. y = (y < min.y) ? min.y : y;
  3460. var z = value.z;
  3461. z = (z > max.z) ? max.z : z;
  3462. z = (z < min.z) ? min.z : z;
  3463. return new Vector3(x, y, z);
  3464. };
  3465. /**
  3466. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3467. * @param value1 defines the first control point
  3468. * @param tangent1 defines the first tangent vector
  3469. * @param value2 defines the second control point
  3470. * @param tangent2 defines the second tangent vector
  3471. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3472. * @returns the new Vector3
  3473. */
  3474. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3475. var squared = amount * amount;
  3476. var cubed = amount * squared;
  3477. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3478. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3479. var part3 = (cubed - (2.0 * squared)) + amount;
  3480. var part4 = cubed - squared;
  3481. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3482. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3483. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3484. return new Vector3(x, y, z);
  3485. };
  3486. /**
  3487. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3488. * @param start defines the start value
  3489. * @param end defines the end value
  3490. * @param amount max defines amount between both (between 0 and 1)
  3491. * @returns the new Vector3
  3492. */
  3493. Vector3.Lerp = function (start, end, amount) {
  3494. var result = new Vector3(0, 0, 0);
  3495. Vector3.LerpToRef(start, end, amount, result);
  3496. return result;
  3497. };
  3498. /**
  3499. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3500. * @param start defines the start value
  3501. * @param end defines the end value
  3502. * @param amount max defines amount between both (between 0 and 1)
  3503. * @param result defines the Vector3 where to store the result
  3504. */
  3505. Vector3.LerpToRef = function (start, end, amount, result) {
  3506. result.x = start.x + ((end.x - start.x) * amount);
  3507. result.y = start.y + ((end.y - start.y) * amount);
  3508. result.z = start.z + ((end.z - start.z) * amount);
  3509. };
  3510. /**
  3511. * Returns the dot product (float) between the vectors "left" and "right"
  3512. * @param left defines the left operand
  3513. * @param right defines the right operand
  3514. * @returns the dot product
  3515. */
  3516. Vector3.Dot = function (left, right) {
  3517. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3518. };
  3519. /**
  3520. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3521. * The cross product is then orthogonal to both "left" and "right"
  3522. * @param left defines the left operand
  3523. * @param right defines the right operand
  3524. * @returns the cross product
  3525. */
  3526. Vector3.Cross = function (left, right) {
  3527. var result = Vector3.Zero();
  3528. Vector3.CrossToRef(left, right, result);
  3529. return result;
  3530. };
  3531. /**
  3532. * Sets the given vector "result" with the cross product of "left" and "right"
  3533. * The cross product is then orthogonal to both "left" and "right"
  3534. * @param left defines the left operand
  3535. * @param right defines the right operand
  3536. * @param result defines the Vector3 where to store the result
  3537. */
  3538. Vector3.CrossToRef = function (left, right, result) {
  3539. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3540. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3541. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3542. result.copyFrom(MathTmp.Vector3[0]);
  3543. };
  3544. /**
  3545. * Returns a new Vector3 as the normalization of the given vector
  3546. * @param vector defines the Vector3 to normalize
  3547. * @returns the new Vector3
  3548. */
  3549. Vector3.Normalize = function (vector) {
  3550. var result = Vector3.Zero();
  3551. Vector3.NormalizeToRef(vector, result);
  3552. return result;
  3553. };
  3554. /**
  3555. * Sets the given vector "result" with the normalization of the given first vector
  3556. * @param vector defines the Vector3 to normalize
  3557. * @param result defines the Vector3 where to store the result
  3558. */
  3559. Vector3.NormalizeToRef = function (vector, result) {
  3560. result.copyFrom(vector);
  3561. result.normalize();
  3562. };
  3563. /**
  3564. * Project a Vector3 onto screen space
  3565. * @param vector defines the Vector3 to project
  3566. * @param world defines the world matrix to use
  3567. * @param transform defines the transform (view x projection) matrix to use
  3568. * @param viewport defines the screen viewport to use
  3569. * @returns the new Vector3
  3570. */
  3571. Vector3.Project = function (vector, world, transform, viewport) {
  3572. var cw = viewport.width;
  3573. var ch = viewport.height;
  3574. var cx = viewport.x;
  3575. var cy = viewport.y;
  3576. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3577. 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);
  3578. var matrix = MathTmp.Matrix[0];
  3579. world.multiplyToRef(transform, matrix);
  3580. matrix.multiplyToRef(viewportMatrix, matrix);
  3581. return Vector3.TransformCoordinates(vector, matrix);
  3582. };
  3583. /**
  3584. * Unproject from screen space to object space
  3585. * @param source defines the screen space Vector3 to use
  3586. * @param viewportWidth defines the current width of the viewport
  3587. * @param viewportHeight defines the current height of the viewport
  3588. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3589. * @param transform defines the transform (view x projection) matrix to use
  3590. * @returns the new Vector3
  3591. */
  3592. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3593. var matrix = MathTmp.Matrix[0];
  3594. world.multiplyToRef(transform, matrix);
  3595. matrix.invert();
  3596. source.x = source.x / viewportWidth * 2 - 1;
  3597. source.y = -(source.y / viewportHeight * 2 - 1);
  3598. var vector = Vector3.TransformCoordinates(source, matrix);
  3599. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3600. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3601. vector = vector.scale(1.0 / num);
  3602. }
  3603. return vector;
  3604. };
  3605. /**
  3606. * Unproject from screen space to object space
  3607. * @param source defines the screen space Vector3 to use
  3608. * @param viewportWidth defines the current width of the viewport
  3609. * @param viewportHeight defines the current height of the viewport
  3610. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3611. * @param view defines the view matrix to use
  3612. * @param projection defines the projection matrix to use
  3613. * @returns the new Vector3
  3614. */
  3615. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3616. var result = Vector3.Zero();
  3617. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3618. return result;
  3619. };
  3620. /**
  3621. * Unproject from screen space to object space
  3622. * @param source defines the screen space Vector3 to use
  3623. * @param viewportWidth defines the current width of the viewport
  3624. * @param viewportHeight defines the current height of the viewport
  3625. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3626. * @param view defines the view matrix to use
  3627. * @param projection defines the projection matrix to use
  3628. * @param result defines the Vector3 where to store the result
  3629. */
  3630. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3631. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3632. };
  3633. /**
  3634. * Unproject from screen space to object space
  3635. * @param sourceX defines the screen space x coordinate to use
  3636. * @param sourceY defines the screen space y coordinate to use
  3637. * @param sourceZ defines the screen space z coordinate to use
  3638. * @param viewportWidth defines the current width of the viewport
  3639. * @param viewportHeight defines the current height of the viewport
  3640. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3641. * @param view defines the view matrix to use
  3642. * @param projection defines the projection matrix to use
  3643. * @param result defines the Vector3 where to store the result
  3644. */
  3645. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3646. var matrix = MathTmp.Matrix[0];
  3647. world.multiplyToRef(view, matrix);
  3648. matrix.multiplyToRef(projection, matrix);
  3649. matrix.invert();
  3650. var screenSource = MathTmp.Vector3[0];
  3651. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3652. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3653. screenSource.z = 2 * sourceZ - 1.0;
  3654. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3655. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3656. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3657. result.scaleInPlace(1.0 / num);
  3658. }
  3659. };
  3660. /**
  3661. * Gets the minimal coordinate values between two Vector3
  3662. * @param left defines the first operand
  3663. * @param right defines the second operand
  3664. * @returns the new Vector3
  3665. */
  3666. Vector3.Minimize = function (left, right) {
  3667. var min = left.clone();
  3668. min.minimizeInPlace(right);
  3669. return min;
  3670. };
  3671. /**
  3672. * Gets the maximal coordinate values between two Vector3
  3673. * @param left defines the first operand
  3674. * @param right defines the second operand
  3675. * @returns the new Vector3
  3676. */
  3677. Vector3.Maximize = function (left, right) {
  3678. var max = left.clone();
  3679. max.maximizeInPlace(right);
  3680. return max;
  3681. };
  3682. /**
  3683. * Returns the distance between the vectors "value1" and "value2"
  3684. * @param value1 defines the first operand
  3685. * @param value2 defines the second operand
  3686. * @returns the distance
  3687. */
  3688. Vector3.Distance = function (value1, value2) {
  3689. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3690. };
  3691. /**
  3692. * Returns the squared distance between the vectors "value1" and "value2"
  3693. * @param value1 defines the first operand
  3694. * @param value2 defines the second operand
  3695. * @returns the squared distance
  3696. */
  3697. Vector3.DistanceSquared = function (value1, value2) {
  3698. var x = value1.x - value2.x;
  3699. var y = value1.y - value2.y;
  3700. var z = value1.z - value2.z;
  3701. return (x * x) + (y * y) + (z * z);
  3702. };
  3703. /**
  3704. * Returns a new Vector3 located at the center between "value1" and "value2"
  3705. * @param value1 defines the first operand
  3706. * @param value2 defines the second operand
  3707. * @returns the new Vector3
  3708. */
  3709. Vector3.Center = function (value1, value2) {
  3710. var center = value1.add(value2);
  3711. center.scaleInPlace(0.5);
  3712. return center;
  3713. };
  3714. /**
  3715. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3716. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3717. * to something in order to rotate it from its local system to the given target system
  3718. * Note: axis1, axis2 and axis3 are normalized during this operation
  3719. * @param axis1 defines the first axis
  3720. * @param axis2 defines the second axis
  3721. * @param axis3 defines the third axis
  3722. * @returns a new Vector3
  3723. */
  3724. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3725. var rotation = Vector3.Zero();
  3726. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3727. return rotation;
  3728. };
  3729. /**
  3730. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3731. * @param axis1 defines the first axis
  3732. * @param axis2 defines the second axis
  3733. * @param axis3 defines the third axis
  3734. * @param ref defines the Vector3 where to store the result
  3735. */
  3736. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3737. var quat = MathTmp.Quaternion[0];
  3738. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3739. quat.toEulerAnglesToRef(ref);
  3740. };
  3741. return Vector3;
  3742. }());
  3743. BABYLON.Vector3 = Vector3;
  3744. //Vector4 class created for EulerAngle class conversion to Quaternion
  3745. var Vector4 = /** @class */ (function () {
  3746. /**
  3747. * Creates a Vector4 object from the given floats.
  3748. */
  3749. function Vector4(x, y, z, w) {
  3750. this.x = x;
  3751. this.y = y;
  3752. this.z = z;
  3753. this.w = w;
  3754. }
  3755. /**
  3756. * Returns the string with the Vector4 coordinates.
  3757. */
  3758. Vector4.prototype.toString = function () {
  3759. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3760. };
  3761. /**
  3762. * Returns the string "Vector4".
  3763. */
  3764. Vector4.prototype.getClassName = function () {
  3765. return "Vector4";
  3766. };
  3767. /**
  3768. * Returns the Vector4 hash code.
  3769. */
  3770. Vector4.prototype.getHashCode = function () {
  3771. var hash = this.x || 0;
  3772. hash = (hash * 397) ^ (this.y || 0);
  3773. hash = (hash * 397) ^ (this.z || 0);
  3774. hash = (hash * 397) ^ (this.w || 0);
  3775. return hash;
  3776. };
  3777. // Operators
  3778. /**
  3779. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3780. */
  3781. Vector4.prototype.asArray = function () {
  3782. var result = new Array();
  3783. this.toArray(result, 0);
  3784. return result;
  3785. };
  3786. /**
  3787. * Populates the given array from the given index with the Vector4 coordinates.
  3788. * Returns the Vector4.
  3789. */
  3790. Vector4.prototype.toArray = function (array, index) {
  3791. if (index === undefined) {
  3792. index = 0;
  3793. }
  3794. array[index] = this.x;
  3795. array[index + 1] = this.y;
  3796. array[index + 2] = this.z;
  3797. array[index + 3] = this.w;
  3798. return this;
  3799. };
  3800. /**
  3801. * Adds the given vector to the current Vector4.
  3802. * Returns the updated Vector4.
  3803. */
  3804. Vector4.prototype.addInPlace = function (otherVector) {
  3805. this.x += otherVector.x;
  3806. this.y += otherVector.y;
  3807. this.z += otherVector.z;
  3808. this.w += otherVector.w;
  3809. return this;
  3810. };
  3811. /**
  3812. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3813. */
  3814. Vector4.prototype.add = function (otherVector) {
  3815. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3816. };
  3817. /**
  3818. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3819. * Returns the current Vector4.
  3820. */
  3821. Vector4.prototype.addToRef = function (otherVector, result) {
  3822. result.x = this.x + otherVector.x;
  3823. result.y = this.y + otherVector.y;
  3824. result.z = this.z + otherVector.z;
  3825. result.w = this.w + otherVector.w;
  3826. return this;
  3827. };
  3828. /**
  3829. * Subtract in place the given vector from the current Vector4.
  3830. * Returns the updated Vector4.
  3831. */
  3832. Vector4.prototype.subtractInPlace = function (otherVector) {
  3833. this.x -= otherVector.x;
  3834. this.y -= otherVector.y;
  3835. this.z -= otherVector.z;
  3836. this.w -= otherVector.w;
  3837. return this;
  3838. };
  3839. /**
  3840. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3841. */
  3842. Vector4.prototype.subtract = function (otherVector) {
  3843. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3844. };
  3845. /**
  3846. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3847. * Returns the current Vector4.
  3848. */
  3849. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3850. result.x = this.x - otherVector.x;
  3851. result.y = this.y - otherVector.y;
  3852. result.z = this.z - otherVector.z;
  3853. result.w = this.w - otherVector.w;
  3854. return this;
  3855. };
  3856. /**
  3857. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3858. */
  3859. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3860. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3861. };
  3862. /**
  3863. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3864. * Returns the current Vector4.
  3865. */
  3866. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3867. result.x = this.x - x;
  3868. result.y = this.y - y;
  3869. result.z = this.z - z;
  3870. result.w = this.w - w;
  3871. return this;
  3872. };
  3873. /**
  3874. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3875. */
  3876. Vector4.prototype.negate = function () {
  3877. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3878. };
  3879. /**
  3880. * Multiplies the current Vector4 coordinates by scale (float).
  3881. * Returns the updated Vector4.
  3882. */
  3883. Vector4.prototype.scaleInPlace = function (scale) {
  3884. this.x *= scale;
  3885. this.y *= scale;
  3886. this.z *= scale;
  3887. this.w *= scale;
  3888. return this;
  3889. };
  3890. /**
  3891. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3892. */
  3893. Vector4.prototype.scale = function (scale) {
  3894. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3895. };
  3896. /**
  3897. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3898. * Returns the current Vector4.
  3899. */
  3900. Vector4.prototype.scaleToRef = function (scale, result) {
  3901. result.x = this.x * scale;
  3902. result.y = this.y * scale;
  3903. result.z = this.z * scale;
  3904. result.w = this.w * scale;
  3905. return this;
  3906. };
  3907. /**
  3908. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3909. * @param scale defines the scale factor
  3910. * @param result defines the Vector4 object where to store the result
  3911. * @returns the unmodified current Vector4
  3912. */
  3913. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3914. result.x += this.x * scale;
  3915. result.y += this.y * scale;
  3916. result.z += this.z * scale;
  3917. result.w += this.w * scale;
  3918. return this;
  3919. };
  3920. /**
  3921. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3922. */
  3923. Vector4.prototype.equals = function (otherVector) {
  3924. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3925. };
  3926. /**
  3927. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3928. */
  3929. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3930. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3931. return otherVector
  3932. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3933. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3934. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3935. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3936. };
  3937. /**
  3938. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3939. */
  3940. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3941. return this.x === x && this.y === y && this.z === z && this.w === w;
  3942. };
  3943. /**
  3944. * Multiplies in place the current Vector4 by the given one.
  3945. * Returns the updated Vector4.
  3946. */
  3947. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3948. this.x *= otherVector.x;
  3949. this.y *= otherVector.y;
  3950. this.z *= otherVector.z;
  3951. this.w *= otherVector.w;
  3952. return this;
  3953. };
  3954. /**
  3955. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3956. */
  3957. Vector4.prototype.multiply = function (otherVector) {
  3958. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3959. };
  3960. /**
  3961. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3962. * Returns the current Vector4.
  3963. */
  3964. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3965. result.x = this.x * otherVector.x;
  3966. result.y = this.y * otherVector.y;
  3967. result.z = this.z * otherVector.z;
  3968. result.w = this.w * otherVector.w;
  3969. return this;
  3970. };
  3971. /**
  3972. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3973. */
  3974. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3975. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3976. };
  3977. /**
  3978. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3979. */
  3980. Vector4.prototype.divide = function (otherVector) {
  3981. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3982. };
  3983. /**
  3984. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  3985. * Returns the current Vector4.
  3986. */
  3987. Vector4.prototype.divideToRef = function (otherVector, result) {
  3988. result.x = this.x / otherVector.x;
  3989. result.y = this.y / otherVector.y;
  3990. result.z = this.z / otherVector.z;
  3991. result.w = this.w / otherVector.w;
  3992. return this;
  3993. };
  3994. /**
  3995. * Divides the current Vector3 coordinates by the given ones.
  3996. * @returns the updated Vector3.
  3997. */
  3998. Vector4.prototype.divideInPlace = function (otherVector) {
  3999. return this.divideToRef(otherVector, this);
  4000. };
  4001. /**
  4002. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4003. * @param other defines the second operand
  4004. * @returns the current updated Vector4
  4005. */
  4006. Vector4.prototype.minimizeInPlace = function (other) {
  4007. if (other.x < this.x)
  4008. this.x = other.x;
  4009. if (other.y < this.y)
  4010. this.y = other.y;
  4011. if (other.z < this.z)
  4012. this.z = other.z;
  4013. if (other.w < this.w)
  4014. this.w = other.w;
  4015. return this;
  4016. };
  4017. /**
  4018. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4019. * @param other defines the second operand
  4020. * @returns the current updated Vector4
  4021. */
  4022. Vector4.prototype.maximizeInPlace = function (other) {
  4023. if (other.x > this.x)
  4024. this.x = other.x;
  4025. if (other.y > this.y)
  4026. this.y = other.y;
  4027. if (other.z > this.z)
  4028. this.z = other.z;
  4029. if (other.w > this.w)
  4030. this.w = other.w;
  4031. return this;
  4032. };
  4033. // Properties
  4034. /**
  4035. * Returns the Vector4 length (float).
  4036. */
  4037. Vector4.prototype.length = function () {
  4038. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4039. };
  4040. /**
  4041. * Returns the Vector4 squared length (float).
  4042. */
  4043. Vector4.prototype.lengthSquared = function () {
  4044. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4045. };
  4046. // Methods
  4047. /**
  4048. * Normalizes in place the Vector4.
  4049. * Returns the updated Vector4.
  4050. */
  4051. Vector4.prototype.normalize = function () {
  4052. var len = this.length();
  4053. if (len === 0)
  4054. return this;
  4055. var num = 1.0 / len;
  4056. this.x *= num;
  4057. this.y *= num;
  4058. this.z *= num;
  4059. this.w *= num;
  4060. return this;
  4061. };
  4062. /**
  4063. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4064. */
  4065. Vector4.prototype.toVector3 = function () {
  4066. return new Vector3(this.x, this.y, this.z);
  4067. };
  4068. /**
  4069. * Returns a new Vector4 copied from the current one.
  4070. */
  4071. Vector4.prototype.clone = function () {
  4072. return new Vector4(this.x, this.y, this.z, this.w);
  4073. };
  4074. /**
  4075. * Updates the current Vector4 with the given one coordinates.
  4076. * Returns the updated Vector4.
  4077. */
  4078. Vector4.prototype.copyFrom = function (source) {
  4079. this.x = source.x;
  4080. this.y = source.y;
  4081. this.z = source.z;
  4082. this.w = source.w;
  4083. return this;
  4084. };
  4085. /**
  4086. * Updates the current Vector4 coordinates with the given floats.
  4087. * Returns the updated Vector4.
  4088. */
  4089. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4090. this.x = x;
  4091. this.y = y;
  4092. this.z = z;
  4093. this.w = w;
  4094. return this;
  4095. };
  4096. /**
  4097. * Updates the current Vector4 coordinates with the given floats.
  4098. * Returns the updated Vector4.
  4099. */
  4100. Vector4.prototype.set = function (x, y, z, w) {
  4101. return this.copyFromFloats(x, y, z, w);
  4102. };
  4103. // Statics
  4104. /**
  4105. * Returns a new Vector4 set from the starting index of the given array.
  4106. */
  4107. Vector4.FromArray = function (array, offset) {
  4108. if (!offset) {
  4109. offset = 0;
  4110. }
  4111. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4112. };
  4113. /**
  4114. * Updates the given vector "result" from the starting index of the given array.
  4115. */
  4116. Vector4.FromArrayToRef = function (array, offset, result) {
  4117. result.x = array[offset];
  4118. result.y = array[offset + 1];
  4119. result.z = array[offset + 2];
  4120. result.w = array[offset + 3];
  4121. };
  4122. /**
  4123. * Updates the given vector "result" from the starting index of the given Float32Array.
  4124. */
  4125. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4126. Vector4.FromArrayToRef(array, offset, result);
  4127. };
  4128. /**
  4129. * Updates the given vector "result" coordinates from the given floats.
  4130. */
  4131. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4132. result.x = x;
  4133. result.y = y;
  4134. result.z = z;
  4135. result.w = w;
  4136. };
  4137. /**
  4138. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4139. */
  4140. Vector4.Zero = function () {
  4141. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4142. };
  4143. /**
  4144. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4145. */
  4146. Vector4.One = function () {
  4147. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4148. };
  4149. /**
  4150. * Returns a new normalized Vector4 from the given one.
  4151. */
  4152. Vector4.Normalize = function (vector) {
  4153. var result = Vector4.Zero();
  4154. Vector4.NormalizeToRef(vector, result);
  4155. return result;
  4156. };
  4157. /**
  4158. * Updates the given vector "result" from the normalization of the given one.
  4159. */
  4160. Vector4.NormalizeToRef = function (vector, result) {
  4161. result.copyFrom(vector);
  4162. result.normalize();
  4163. };
  4164. Vector4.Minimize = function (left, right) {
  4165. var min = left.clone();
  4166. min.minimizeInPlace(right);
  4167. return min;
  4168. };
  4169. Vector4.Maximize = function (left, right) {
  4170. var max = left.clone();
  4171. max.maximizeInPlace(right);
  4172. return max;
  4173. };
  4174. /**
  4175. * Returns the distance (float) between the vectors "value1" and "value2".
  4176. */
  4177. Vector4.Distance = function (value1, value2) {
  4178. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4179. };
  4180. /**
  4181. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4182. */
  4183. Vector4.DistanceSquared = function (value1, value2) {
  4184. var x = value1.x - value2.x;
  4185. var y = value1.y - value2.y;
  4186. var z = value1.z - value2.z;
  4187. var w = value1.w - value2.w;
  4188. return (x * x) + (y * y) + (z * z) + (w * w);
  4189. };
  4190. /**
  4191. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4192. */
  4193. Vector4.Center = function (value1, value2) {
  4194. var center = value1.add(value2);
  4195. center.scaleInPlace(0.5);
  4196. return center;
  4197. };
  4198. /**
  4199. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4200. * This methods computes transformed normalized direction vectors only.
  4201. */
  4202. Vector4.TransformNormal = function (vector, transformation) {
  4203. var result = Vector4.Zero();
  4204. Vector4.TransformNormalToRef(vector, transformation, result);
  4205. return result;
  4206. };
  4207. /**
  4208. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4209. * This methods computes transformed normalized direction vectors only.
  4210. */
  4211. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4212. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4213. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4214. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4215. result.x = x;
  4216. result.y = y;
  4217. result.z = z;
  4218. result.w = vector.w;
  4219. };
  4220. /**
  4221. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4222. * This methods computes transformed normalized direction vectors only.
  4223. */
  4224. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4225. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4226. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4227. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4228. result.w = w;
  4229. };
  4230. return Vector4;
  4231. }());
  4232. BABYLON.Vector4 = Vector4;
  4233. var Size = /** @class */ (function () {
  4234. /**
  4235. * Creates a Size object from the given width and height (floats).
  4236. */
  4237. function Size(width, height) {
  4238. this.width = width;
  4239. this.height = height;
  4240. }
  4241. // Returns a string with the Size width and height.
  4242. Size.prototype.toString = function () {
  4243. return "{W: " + this.width + ", H: " + this.height + "}";
  4244. };
  4245. /**
  4246. * Returns the string "Size"
  4247. */
  4248. Size.prototype.getClassName = function () {
  4249. return "Size";
  4250. };
  4251. /**
  4252. * Returns the Size hash code.
  4253. */
  4254. Size.prototype.getHashCode = function () {
  4255. var hash = this.width || 0;
  4256. hash = (hash * 397) ^ (this.height || 0);
  4257. return hash;
  4258. };
  4259. /**
  4260. * Updates the current size from the given one.
  4261. * Returns the updated Size.
  4262. */
  4263. Size.prototype.copyFrom = function (src) {
  4264. this.width = src.width;
  4265. this.height = src.height;
  4266. };
  4267. /**
  4268. * Updates in place the current Size from the given floats.
  4269. * Returns the updated Size.
  4270. */
  4271. Size.prototype.copyFromFloats = function (width, height) {
  4272. this.width = width;
  4273. this.height = height;
  4274. return this;
  4275. };
  4276. /**
  4277. * Updates in place the current Size from the given floats.
  4278. * Returns the updated Size.
  4279. */
  4280. Size.prototype.set = function (width, height) {
  4281. return this.copyFromFloats(width, height);
  4282. };
  4283. /**
  4284. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4285. */
  4286. Size.prototype.multiplyByFloats = function (w, h) {
  4287. return new Size(this.width * w, this.height * h);
  4288. };
  4289. /**
  4290. * Returns a new Size copied from the given one.
  4291. */
  4292. Size.prototype.clone = function () {
  4293. return new Size(this.width, this.height);
  4294. };
  4295. /**
  4296. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4297. */
  4298. Size.prototype.equals = function (other) {
  4299. if (!other) {
  4300. return false;
  4301. }
  4302. return (this.width === other.width) && (this.height === other.height);
  4303. };
  4304. Object.defineProperty(Size.prototype, "surface", {
  4305. /**
  4306. * Returns the surface of the Size : width * height (float).
  4307. */
  4308. get: function () {
  4309. return this.width * this.height;
  4310. },
  4311. enumerable: true,
  4312. configurable: true
  4313. });
  4314. /**
  4315. * Returns a new Size set to (0.0, 0.0)
  4316. */
  4317. Size.Zero = function () {
  4318. return new Size(0.0, 0.0);
  4319. };
  4320. /**
  4321. * Returns a new Size set as the addition result of the current Size and the given one.
  4322. */
  4323. Size.prototype.add = function (otherSize) {
  4324. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4325. return r;
  4326. };
  4327. /**
  4328. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4329. */
  4330. Size.prototype.subtract = function (otherSize) {
  4331. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4332. return r;
  4333. };
  4334. /**
  4335. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4336. */
  4337. Size.Lerp = function (start, end, amount) {
  4338. var w = start.width + ((end.width - start.width) * amount);
  4339. var h = start.height + ((end.height - start.height) * amount);
  4340. return new Size(w, h);
  4341. };
  4342. return Size;
  4343. }());
  4344. BABYLON.Size = Size;
  4345. /**
  4346. * Class used to store quaternion data
  4347. * @see https://en.wikipedia.org/wiki/Quaternion
  4348. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4349. */
  4350. var Quaternion = /** @class */ (function () {
  4351. /**
  4352. * Creates a new Quaternion from the given floats
  4353. * @param x defines the first component (0 by default)
  4354. * @param y defines the second component (0 by default)
  4355. * @param z defines the third component (0 by default)
  4356. * @param w defines the fourth component (1.0 by default)
  4357. */
  4358. function Quaternion(
  4359. /** defines the first component (0 by default) */
  4360. x,
  4361. /** defines the second component (0 by default) */
  4362. y,
  4363. /** defines the third component (0 by default) */
  4364. z,
  4365. /** defines the fourth component (1.0 by default) */
  4366. w) {
  4367. if (x === void 0) { x = 0.0; }
  4368. if (y === void 0) { y = 0.0; }
  4369. if (z === void 0) { z = 0.0; }
  4370. if (w === void 0) { w = 1.0; }
  4371. this.x = x;
  4372. this.y = y;
  4373. this.z = z;
  4374. this.w = w;
  4375. }
  4376. /**
  4377. * Gets a string representation for the current quaternion
  4378. * @returns a string with the Quaternion coordinates
  4379. */
  4380. Quaternion.prototype.toString = function () {
  4381. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4382. };
  4383. /**
  4384. * Gets the class name of the quaternion
  4385. * @returns the string "Quaternion"
  4386. */
  4387. Quaternion.prototype.getClassName = function () {
  4388. return "Quaternion";
  4389. };
  4390. /**
  4391. * Gets a hash code for this quaternion
  4392. * @returns the quaternion hash code
  4393. */
  4394. Quaternion.prototype.getHashCode = function () {
  4395. var hash = this.x || 0;
  4396. hash = (hash * 397) ^ (this.y || 0);
  4397. hash = (hash * 397) ^ (this.z || 0);
  4398. hash = (hash * 397) ^ (this.w || 0);
  4399. return hash;
  4400. };
  4401. /**
  4402. * Copy the quaternion to an array
  4403. * @returns a new array populated with 4 elements from the quaternion coordinates
  4404. */
  4405. Quaternion.prototype.asArray = function () {
  4406. return [this.x, this.y, this.z, this.w];
  4407. };
  4408. /**
  4409. * Check if two quaternions are equals
  4410. * @param otherQuaternion defines the second operand
  4411. * @return true if the current quaternion and the given one coordinates are strictly equals
  4412. */
  4413. Quaternion.prototype.equals = function (otherQuaternion) {
  4414. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4415. };
  4416. /**
  4417. * Clone the current quaternion
  4418. * @returns a new quaternion copied from the current one
  4419. */
  4420. Quaternion.prototype.clone = function () {
  4421. return new Quaternion(this.x, this.y, this.z, this.w);
  4422. };
  4423. /**
  4424. * Copy a quaternion to the current one
  4425. * @param other defines the other quaternion
  4426. * @returns the updated current quaternion
  4427. */
  4428. Quaternion.prototype.copyFrom = function (other) {
  4429. this.x = other.x;
  4430. this.y = other.y;
  4431. this.z = other.z;
  4432. this.w = other.w;
  4433. return this;
  4434. };
  4435. /**
  4436. * Updates the current quaternion with the given float coordinates
  4437. * @param x defines the x coordinate
  4438. * @param y defines the y coordinate
  4439. * @param z defines the z coordinate
  4440. * @param w defines the w coordinate
  4441. * @returns the updated current quaternion
  4442. */
  4443. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4444. this.x = x;
  4445. this.y = y;
  4446. this.z = z;
  4447. this.w = w;
  4448. return this;
  4449. };
  4450. /**
  4451. * Updates the current quaternion from the given float coordinates
  4452. * @param x defines the x coordinate
  4453. * @param y defines the y coordinate
  4454. * @param z defines the z coordinate
  4455. * @param w defines the w coordinate
  4456. * @returns the updated current quaternion
  4457. */
  4458. Quaternion.prototype.set = function (x, y, z, w) {
  4459. return this.copyFromFloats(x, y, z, w);
  4460. };
  4461. /**
  4462. * Adds two quaternions
  4463. * @param other defines the second operand
  4464. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4465. */
  4466. Quaternion.prototype.add = function (other) {
  4467. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4468. };
  4469. /**
  4470. * Add a quaternion to the current one
  4471. * @param other defines the quaternion to add
  4472. * @returns the current quaternion
  4473. */
  4474. Quaternion.prototype.addInPlace = function (other) {
  4475. this.x += other.x;
  4476. this.y += other.y;
  4477. this.z += other.z;
  4478. this.w += other.w;
  4479. return this;
  4480. };
  4481. /**
  4482. * Subtract two quaternions
  4483. * @param other defines the second operand
  4484. * @returns a new quaternion as the subtraction result of the given one from the current one
  4485. */
  4486. Quaternion.prototype.subtract = function (other) {
  4487. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4488. };
  4489. /**
  4490. * Multiplies the current quaternion by a scale factor
  4491. * @param value defines the scale factor
  4492. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4493. */
  4494. Quaternion.prototype.scale = function (value) {
  4495. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4496. };
  4497. /**
  4498. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4499. * @param scale defines the scale factor
  4500. * @param result defines the Quaternion object where to store the result
  4501. * @returns the unmodified current quaternion
  4502. */
  4503. Quaternion.prototype.scaleToRef = function (scale, result) {
  4504. result.x = this.x * scale;
  4505. result.y = this.y * scale;
  4506. result.z = this.z * scale;
  4507. result.w = this.w * scale;
  4508. return this;
  4509. };
  4510. /**
  4511. * Multiplies in place the current quaternion by a scale factor
  4512. * @param value defines the scale factor
  4513. * @returns the current modified quaternion
  4514. */
  4515. Quaternion.prototype.scaleInPlace = function (value) {
  4516. this.x *= value;
  4517. this.y *= value;
  4518. this.z *= value;
  4519. this.w *= value;
  4520. return this;
  4521. };
  4522. /**
  4523. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4524. * @param scale defines the scale factor
  4525. * @param result defines the Quaternion object where to store the result
  4526. * @returns the unmodified current quaternion
  4527. */
  4528. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4529. result.x += this.x * scale;
  4530. result.y += this.y * scale;
  4531. result.z += this.z * scale;
  4532. result.w += this.w * scale;
  4533. return this;
  4534. };
  4535. /**
  4536. * Multiplies two quaternions
  4537. * @param q1 defines the second operand
  4538. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4539. */
  4540. Quaternion.prototype.multiply = function (q1) {
  4541. var result = new Quaternion(0, 0, 0, 1.0);
  4542. this.multiplyToRef(q1, result);
  4543. return result;
  4544. };
  4545. /**
  4546. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4547. * @param q1 defines the second operand
  4548. * @param result defines the target quaternion
  4549. * @returns the current quaternion
  4550. */
  4551. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4552. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4553. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4554. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4555. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4556. result.copyFromFloats(x, y, z, w);
  4557. return this;
  4558. };
  4559. /**
  4560. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4561. * @param q1 defines the second operand
  4562. * @returns the currentupdated quaternion
  4563. */
  4564. Quaternion.prototype.multiplyInPlace = function (q1) {
  4565. this.multiplyToRef(q1, this);
  4566. return this;
  4567. };
  4568. /**
  4569. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4570. * @param ref defines the target quaternion
  4571. * @returns the current quaternion
  4572. */
  4573. Quaternion.prototype.conjugateToRef = function (ref) {
  4574. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4575. return this;
  4576. };
  4577. /**
  4578. * Conjugates in place (1-q) the current quaternion
  4579. * @returns the current updated quaternion
  4580. */
  4581. Quaternion.prototype.conjugateInPlace = function () {
  4582. this.x *= -1;
  4583. this.y *= -1;
  4584. this.z *= -1;
  4585. return this;
  4586. };
  4587. /**
  4588. * Conjugates in place (1-q) the current quaternion
  4589. * @returns a new quaternion
  4590. */
  4591. Quaternion.prototype.conjugate = function () {
  4592. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4593. return result;
  4594. };
  4595. /**
  4596. * Gets length of current quaternion
  4597. * @returns the quaternion length (float)
  4598. */
  4599. Quaternion.prototype.length = function () {
  4600. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4601. };
  4602. /**
  4603. * Normalize in place the current quaternion
  4604. * @returns the current updated quaternion
  4605. */
  4606. Quaternion.prototype.normalize = function () {
  4607. var length = 1.0 / this.length();
  4608. this.x *= length;
  4609. this.y *= length;
  4610. this.z *= length;
  4611. this.w *= length;
  4612. return this;
  4613. };
  4614. /**
  4615. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4616. * @param order is a reserved parameter and is ignore for now
  4617. * @returns a new Vector3 containing the Euler angles
  4618. */
  4619. Quaternion.prototype.toEulerAngles = function (order) {
  4620. if (order === void 0) { order = "YZX"; }
  4621. var result = Vector3.Zero();
  4622. this.toEulerAnglesToRef(result, order);
  4623. return result;
  4624. };
  4625. /**
  4626. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4627. * @param result defines the vector which will be filled with the Euler angles
  4628. * @param order is a reserved parameter and is ignore for now
  4629. * @returns the current unchanged quaternion
  4630. */
  4631. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4632. if (order === void 0) { order = "YZX"; }
  4633. var qz = this.z;
  4634. var qx = this.x;
  4635. var qy = this.y;
  4636. var qw = this.w;
  4637. var sqw = qw * qw;
  4638. var sqz = qz * qz;
  4639. var sqx = qx * qx;
  4640. var sqy = qy * qy;
  4641. var zAxisY = qy * qz - qx * qw;
  4642. var limit = .4999999;
  4643. if (zAxisY < -limit) {
  4644. result.y = 2 * Math.atan2(qy, qw);
  4645. result.x = Math.PI / 2;
  4646. result.z = 0;
  4647. }
  4648. else if (zAxisY > limit) {
  4649. result.y = 2 * Math.atan2(qy, qw);
  4650. result.x = -Math.PI / 2;
  4651. result.z = 0;
  4652. }
  4653. else {
  4654. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4655. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4656. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4657. }
  4658. return this;
  4659. };
  4660. /**
  4661. * Updates the given rotation matrix with the current quaternion values
  4662. * @param result defines the target matrix
  4663. * @returns the current unchanged quaternion
  4664. */
  4665. Quaternion.prototype.toRotationMatrix = function (result) {
  4666. var xx = this.x * this.x;
  4667. var yy = this.y * this.y;
  4668. var zz = this.z * this.z;
  4669. var xy = this.x * this.y;
  4670. var zw = this.z * this.w;
  4671. var zx = this.z * this.x;
  4672. var yw = this.y * this.w;
  4673. var yz = this.y * this.z;
  4674. var xw = this.x * this.w;
  4675. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4676. result.m[1] = 2.0 * (xy + zw);
  4677. result.m[2] = 2.0 * (zx - yw);
  4678. result.m[3] = 0;
  4679. result.m[4] = 2.0 * (xy - zw);
  4680. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4681. result.m[6] = 2.0 * (yz + xw);
  4682. result.m[7] = 0;
  4683. result.m[8] = 2.0 * (zx + yw);
  4684. result.m[9] = 2.0 * (yz - xw);
  4685. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4686. result.m[11] = 0;
  4687. result.m[12] = 0;
  4688. result.m[13] = 0;
  4689. result.m[14] = 0;
  4690. result.m[15] = 1.0;
  4691. result._markAsUpdated();
  4692. return this;
  4693. };
  4694. /**
  4695. * Updates the current quaternion from the given rotation matrix values
  4696. * @param matrix defines the source matrix
  4697. * @returns the current updated quaternion
  4698. */
  4699. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4700. Quaternion.FromRotationMatrixToRef(matrix, this);
  4701. return this;
  4702. };
  4703. // Statics
  4704. /**
  4705. * Creates a new quaternion from a rotation matrix
  4706. * @param matrix defines the source matrix
  4707. * @returns a new quaternion created from the given rotation matrix values
  4708. */
  4709. Quaternion.FromRotationMatrix = function (matrix) {
  4710. var result = new Quaternion();
  4711. Quaternion.FromRotationMatrixToRef(matrix, result);
  4712. return result;
  4713. };
  4714. /**
  4715. * Updates the given quaternion with the given rotation matrix values
  4716. * @param matrix defines the source matrix
  4717. * @param result defines the target quaternion
  4718. */
  4719. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4720. var data = matrix.m;
  4721. var m11 = data[0], m12 = data[4], m13 = data[8];
  4722. var m21 = data[1], m22 = data[5], m23 = data[9];
  4723. var m31 = data[2], m32 = data[6], m33 = data[10];
  4724. var trace = m11 + m22 + m33;
  4725. var s;
  4726. if (trace > 0) {
  4727. s = 0.5 / Math.sqrt(trace + 1.0);
  4728. result.w = 0.25 / s;
  4729. result.x = (m32 - m23) * s;
  4730. result.y = (m13 - m31) * s;
  4731. result.z = (m21 - m12) * s;
  4732. }
  4733. else if (m11 > m22 && m11 > m33) {
  4734. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4735. result.w = (m32 - m23) / s;
  4736. result.x = 0.25 * s;
  4737. result.y = (m12 + m21) / s;
  4738. result.z = (m13 + m31) / s;
  4739. }
  4740. else if (m22 > m33) {
  4741. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4742. result.w = (m13 - m31) / s;
  4743. result.x = (m12 + m21) / s;
  4744. result.y = 0.25 * s;
  4745. result.z = (m23 + m32) / s;
  4746. }
  4747. else {
  4748. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4749. result.w = (m21 - m12) / s;
  4750. result.x = (m13 + m31) / s;
  4751. result.y = (m23 + m32) / s;
  4752. result.z = 0.25 * s;
  4753. }
  4754. };
  4755. /**
  4756. * Returns the dot product (float) between the quaternions "left" and "right"
  4757. * @param left defines the left operand
  4758. * @param right defines the right operand
  4759. * @returns the dot product
  4760. */
  4761. Quaternion.Dot = function (left, right) {
  4762. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4763. };
  4764. /**
  4765. * Checks if the two quaternions are close to each other
  4766. * @param quat0 defines the first quaternion to check
  4767. * @param quat1 defines the second quaternion to check
  4768. * @returns true if the two quaternions are close to each other
  4769. */
  4770. Quaternion.AreClose = function (quat0, quat1) {
  4771. var dot = Quaternion.Dot(quat0, quat1);
  4772. return dot >= 0;
  4773. };
  4774. /**
  4775. * Creates an empty quaternion
  4776. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4777. */
  4778. Quaternion.Zero = function () {
  4779. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4780. };
  4781. /**
  4782. * Inverse a given quaternion
  4783. * @param q defines the source quaternion
  4784. * @returns a new quaternion as the inverted current quaternion
  4785. */
  4786. Quaternion.Inverse = function (q) {
  4787. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4788. };
  4789. /**
  4790. * Creates an identity quaternion
  4791. * @returns the identity quaternion
  4792. */
  4793. Quaternion.Identity = function () {
  4794. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4795. };
  4796. /**
  4797. * Gets a boolean indicating if the given quaternion is identity
  4798. * @param quaternion defines the quaternion to check
  4799. * @returns true if the quaternion is identity
  4800. */
  4801. Quaternion.IsIdentity = function (quaternion) {
  4802. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4803. };
  4804. /**
  4805. * Creates a quaternion from a rotation around an axis
  4806. * @param axis defines the axis to use
  4807. * @param angle defines the angle to use
  4808. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4809. */
  4810. Quaternion.RotationAxis = function (axis, angle) {
  4811. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4812. };
  4813. /**
  4814. * Creates a rotation around an axis and stores it into the given quaternion
  4815. * @param axis defines the axis to use
  4816. * @param angle defines the angle to use
  4817. * @param result defines the target quaternion
  4818. * @returns the target quaternion
  4819. */
  4820. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4821. var sin = Math.sin(angle / 2);
  4822. axis.normalize();
  4823. result.w = Math.cos(angle / 2);
  4824. result.x = axis.x * sin;
  4825. result.y = axis.y * sin;
  4826. result.z = axis.z * sin;
  4827. return result;
  4828. };
  4829. /**
  4830. * Creates a new quaternion from data stored into an array
  4831. * @param array defines the data source
  4832. * @param offset defines the offset in the source array where the data starts
  4833. * @returns a new quaternion
  4834. */
  4835. Quaternion.FromArray = function (array, offset) {
  4836. if (!offset) {
  4837. offset = 0;
  4838. }
  4839. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4840. };
  4841. /**
  4842. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4843. * @param yaw defines the rotation around Y axis
  4844. * @param pitch defines the rotation around X axis
  4845. * @param roll defines the rotation around Z axis
  4846. * @returns the new quaternion
  4847. */
  4848. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4849. var q = new Quaternion();
  4850. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4851. return q;
  4852. };
  4853. /**
  4854. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4855. * @param yaw defines the rotation around Y axis
  4856. * @param pitch defines the rotation around X axis
  4857. * @param roll defines the rotation around Z axis
  4858. * @param result defines the target quaternion
  4859. */
  4860. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4861. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4862. var halfRoll = roll * 0.5;
  4863. var halfPitch = pitch * 0.5;
  4864. var halfYaw = yaw * 0.5;
  4865. var sinRoll = Math.sin(halfRoll);
  4866. var cosRoll = Math.cos(halfRoll);
  4867. var sinPitch = Math.sin(halfPitch);
  4868. var cosPitch = Math.cos(halfPitch);
  4869. var sinYaw = Math.sin(halfYaw);
  4870. var cosYaw = Math.cos(halfYaw);
  4871. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4872. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4873. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4874. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4875. };
  4876. /**
  4877. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4878. * @param alpha defines the rotation around first axis
  4879. * @param beta defines the rotation around second axis
  4880. * @param gamma defines the rotation around third axis
  4881. * @returns the new quaternion
  4882. */
  4883. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4884. var result = new Quaternion();
  4885. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4886. return result;
  4887. };
  4888. /**
  4889. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4890. * @param alpha defines the rotation around first axis
  4891. * @param beta defines the rotation around second axis
  4892. * @param gamma defines the rotation around third axis
  4893. * @param result defines the target quaternion
  4894. */
  4895. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4896. // Produces a quaternion from Euler angles in the z-x-z orientation
  4897. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4898. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4899. var halfBeta = beta * 0.5;
  4900. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4901. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4902. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4903. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4904. };
  4905. /**
  4906. * 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)
  4907. * @param axis1 defines the first axis
  4908. * @param axis2 defines the second axis
  4909. * @param axis3 defines the third axis
  4910. * @returns the new quaternion
  4911. */
  4912. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4913. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4914. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4915. return quat;
  4916. };
  4917. /**
  4918. * 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
  4919. * @param axis1 defines the first axis
  4920. * @param axis2 defines the second axis
  4921. * @param axis3 defines the third axis
  4922. * @param ref defines the target quaternion
  4923. */
  4924. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4925. var rotMat = MathTmp.Matrix[0];
  4926. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4927. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4928. };
  4929. /**
  4930. * Interpolates between two quaternions
  4931. * @param left defines first quaternion
  4932. * @param right defines second quaternion
  4933. * @param amount defines the gradient to use
  4934. * @returns the new interpolated quaternion
  4935. */
  4936. Quaternion.Slerp = function (left, right, amount) {
  4937. var result = Quaternion.Identity();
  4938. Quaternion.SlerpToRef(left, right, amount, result);
  4939. return result;
  4940. };
  4941. /**
  4942. * Interpolates between two quaternions and stores it into a target quaternion
  4943. * @param left defines first quaternion
  4944. * @param right defines second quaternion
  4945. * @param amount defines the gradient to use
  4946. * @param result defines the target quaternion
  4947. */
  4948. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4949. var num2;
  4950. var num3;
  4951. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4952. var flag = false;
  4953. if (num4 < 0) {
  4954. flag = true;
  4955. num4 = -num4;
  4956. }
  4957. if (num4 > 0.999999) {
  4958. num3 = 1 - amount;
  4959. num2 = flag ? -amount : amount;
  4960. }
  4961. else {
  4962. var num5 = Math.acos(num4);
  4963. var num6 = (1.0 / Math.sin(num5));
  4964. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4965. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4966. }
  4967. result.x = (num3 * left.x) + (num2 * right.x);
  4968. result.y = (num3 * left.y) + (num2 * right.y);
  4969. result.z = (num3 * left.z) + (num2 * right.z);
  4970. result.w = (num3 * left.w) + (num2 * right.w);
  4971. };
  4972. /**
  4973. * Interpolate between two quaternions using Hermite interpolation
  4974. * @param value1 defines first quaternion
  4975. * @param tangent1 defines the incoming tangent
  4976. * @param value2 defines second quaternion
  4977. * @param tangent2 defines the outgoing tangent
  4978. * @param amount defines the target quaternion
  4979. * @returns the new interpolated quaternion
  4980. */
  4981. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4982. var squared = amount * amount;
  4983. var cubed = amount * squared;
  4984. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4985. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4986. var part3 = (cubed - (2.0 * squared)) + amount;
  4987. var part4 = cubed - squared;
  4988. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4989. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4990. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4991. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4992. return new Quaternion(x, y, z, w);
  4993. };
  4994. return Quaternion;
  4995. }());
  4996. BABYLON.Quaternion = Quaternion;
  4997. /**
  4998. * Class used to store matrix data (4x4)
  4999. */
  5000. var Matrix = /** @class */ (function () {
  5001. /**
  5002. * Creates an empty matrix (filled with zeros)
  5003. */
  5004. function Matrix() {
  5005. this._isIdentity = false;
  5006. this._isIdentityDirty = true;
  5007. /**
  5008. * Gets or sets the internal data of the matrix
  5009. */
  5010. this.m = new Float32Array(16);
  5011. this._markAsUpdated();
  5012. }
  5013. /** @hidden */
  5014. Matrix.prototype._markAsUpdated = function () {
  5015. this.updateFlag = Matrix._updateFlagSeed++;
  5016. this._isIdentityDirty = true;
  5017. };
  5018. // Properties
  5019. /**
  5020. * Check if the current matrix is indentity
  5021. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5022. * @returns true is the matrix is the identity matrix
  5023. */
  5024. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5025. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5026. if (this._isIdentityDirty) {
  5027. this._isIdentityDirty = false;
  5028. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5029. this._isIdentity = false;
  5030. }
  5031. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5032. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5033. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5034. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5035. this._isIdentity = false;
  5036. }
  5037. else {
  5038. this._isIdentity = true;
  5039. }
  5040. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5041. this._isIdentity = false;
  5042. }
  5043. }
  5044. return this._isIdentity;
  5045. };
  5046. /**
  5047. * Gets the determinant of the matrix
  5048. * @returns the matrix determinant
  5049. */
  5050. Matrix.prototype.determinant = function () {
  5051. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5052. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5053. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5054. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5055. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5056. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5057. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5058. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5059. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5060. };
  5061. // Methods
  5062. /**
  5063. * Returns the matrix as a Float32Array
  5064. * @returns the matrix underlying array
  5065. */
  5066. Matrix.prototype.toArray = function () {
  5067. return this.m;
  5068. };
  5069. /**
  5070. * Returns the matrix as a Float32Array
  5071. * @returns the matrix underlying array.
  5072. */
  5073. Matrix.prototype.asArray = function () {
  5074. return this.toArray();
  5075. };
  5076. /**
  5077. * Inverts the current matrix in place
  5078. * @returns the current inverted matrix
  5079. */
  5080. Matrix.prototype.invert = function () {
  5081. this.invertToRef(this);
  5082. return this;
  5083. };
  5084. /**
  5085. * Sets all the matrix elements to zero
  5086. * @returns the current matrix
  5087. */
  5088. Matrix.prototype.reset = function () {
  5089. for (var index = 0; index < 16; index++) {
  5090. this.m[index] = 0.0;
  5091. }
  5092. this._markAsUpdated();
  5093. return this;
  5094. };
  5095. /**
  5096. * Adds the current matrix with a second one
  5097. * @param other defines the matrix to add
  5098. * @returns a new matrix as the addition of the current matrix and the given one
  5099. */
  5100. Matrix.prototype.add = function (other) {
  5101. var result = new Matrix();
  5102. this.addToRef(other, result);
  5103. return result;
  5104. };
  5105. /**
  5106. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5107. * @param other defines the matrix to add
  5108. * @param result defines the target matrix
  5109. * @returns the current matrix
  5110. */
  5111. Matrix.prototype.addToRef = function (other, result) {
  5112. for (var index = 0; index < 16; index++) {
  5113. result.m[index] = this.m[index] + other.m[index];
  5114. }
  5115. result._markAsUpdated();
  5116. return this;
  5117. };
  5118. /**
  5119. * Adds in place the given matrix to the current matrix
  5120. * @param other defines the second operand
  5121. * @returns the current updated matrix
  5122. */
  5123. Matrix.prototype.addToSelf = function (other) {
  5124. for (var index = 0; index < 16; index++) {
  5125. this.m[index] += other.m[index];
  5126. }
  5127. this._markAsUpdated();
  5128. return this;
  5129. };
  5130. /**
  5131. * Sets the given matrix to the current inverted Matrix
  5132. * @param other defines the target matrix
  5133. * @returns the unmodified current matrix
  5134. */
  5135. Matrix.prototype.invertToRef = function (other) {
  5136. var l1 = this.m[0];
  5137. var l2 = this.m[1];
  5138. var l3 = this.m[2];
  5139. var l4 = this.m[3];
  5140. var l5 = this.m[4];
  5141. var l6 = this.m[5];
  5142. var l7 = this.m[6];
  5143. var l8 = this.m[7];
  5144. var l9 = this.m[8];
  5145. var l10 = this.m[9];
  5146. var l11 = this.m[10];
  5147. var l12 = this.m[11];
  5148. var l13 = this.m[12];
  5149. var l14 = this.m[13];
  5150. var l15 = this.m[14];
  5151. var l16 = this.m[15];
  5152. var l17 = (l11 * l16) - (l12 * l15);
  5153. var l18 = (l10 * l16) - (l12 * l14);
  5154. var l19 = (l10 * l15) - (l11 * l14);
  5155. var l20 = (l9 * l16) - (l12 * l13);
  5156. var l21 = (l9 * l15) - (l11 * l13);
  5157. var l22 = (l9 * l14) - (l10 * l13);
  5158. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5159. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5160. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5161. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5162. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5163. var l28 = (l7 * l16) - (l8 * l15);
  5164. var l29 = (l6 * l16) - (l8 * l14);
  5165. var l30 = (l6 * l15) - (l7 * l14);
  5166. var l31 = (l5 * l16) - (l8 * l13);
  5167. var l32 = (l5 * l15) - (l7 * l13);
  5168. var l33 = (l5 * l14) - (l6 * l13);
  5169. var l34 = (l7 * l12) - (l8 * l11);
  5170. var l35 = (l6 * l12) - (l8 * l10);
  5171. var l36 = (l6 * l11) - (l7 * l10);
  5172. var l37 = (l5 * l12) - (l8 * l9);
  5173. var l38 = (l5 * l11) - (l7 * l9);
  5174. var l39 = (l5 * l10) - (l6 * l9);
  5175. other.m[0] = l23 * l27;
  5176. other.m[4] = l24 * l27;
  5177. other.m[8] = l25 * l27;
  5178. other.m[12] = l26 * l27;
  5179. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5180. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5181. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5182. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5183. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5184. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5185. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5186. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5187. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5188. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5189. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5190. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5191. other._markAsUpdated();
  5192. return this;
  5193. };
  5194. /**
  5195. * Inserts the translation vector (using 3 floats) in the current matrix
  5196. * @param x defines the 1st component of the translation
  5197. * @param y defines the 2nd component of the translation
  5198. * @param z defines the 3rd component of the translation
  5199. * @returns the current updated matrix
  5200. */
  5201. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5202. this.m[12] = x;
  5203. this.m[13] = y;
  5204. this.m[14] = z;
  5205. this._markAsUpdated();
  5206. return this;
  5207. };
  5208. /**
  5209. * Inserts the translation vector in the current matrix
  5210. * @param vector3 defines the translation to insert
  5211. * @returns the current updated matrix
  5212. */
  5213. Matrix.prototype.setTranslation = function (vector3) {
  5214. this.m[12] = vector3.x;
  5215. this.m[13] = vector3.y;
  5216. this.m[14] = vector3.z;
  5217. this._markAsUpdated();
  5218. return this;
  5219. };
  5220. /**
  5221. * Gets the translation value of the current matrix
  5222. * @returns a new Vector3 as the extracted translation from the matrix
  5223. */
  5224. Matrix.prototype.getTranslation = function () {
  5225. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5226. };
  5227. /**
  5228. * Fill a Vector3 with the extracted translation from the matrix
  5229. * @param result defines the Vector3 where to store the translation
  5230. * @returns the current matrix
  5231. */
  5232. Matrix.prototype.getTranslationToRef = function (result) {
  5233. result.x = this.m[12];
  5234. result.y = this.m[13];
  5235. result.z = this.m[14];
  5236. return this;
  5237. };
  5238. /**
  5239. * Remove rotation and scaling part from the matrix
  5240. * @returns the updated matrix
  5241. */
  5242. Matrix.prototype.removeRotationAndScaling = function () {
  5243. this.setRowFromFloats(0, 1, 0, 0, 0);
  5244. this.setRowFromFloats(1, 0, 1, 0, 0);
  5245. this.setRowFromFloats(2, 0, 0, 1, 0);
  5246. return this;
  5247. };
  5248. /**
  5249. * Multiply two matrices
  5250. * @param other defines the second operand
  5251. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5252. */
  5253. Matrix.prototype.multiply = function (other) {
  5254. var result = new Matrix();
  5255. this.multiplyToRef(other, result);
  5256. return result;
  5257. };
  5258. /**
  5259. * Copy the current matrix from the given one
  5260. * @param other defines the source matrix
  5261. * @returns the current updated matrix
  5262. */
  5263. Matrix.prototype.copyFrom = function (other) {
  5264. for (var index = 0; index < 16; index++) {
  5265. this.m[index] = other.m[index];
  5266. }
  5267. this._markAsUpdated();
  5268. return this;
  5269. };
  5270. /**
  5271. * Populates the given array from the starting index with the current matrix values
  5272. * @param array defines the target array
  5273. * @param offset defines the offset in the target array where to start storing values
  5274. * @returns the current matrix
  5275. */
  5276. Matrix.prototype.copyToArray = function (array, offset) {
  5277. if (offset === void 0) { offset = 0; }
  5278. for (var index = 0; index < 16; index++) {
  5279. array[offset + index] = this.m[index];
  5280. }
  5281. return this;
  5282. };
  5283. /**
  5284. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5285. * @param other defines the second operand
  5286. * @param result defines the matrix where to store the multiplication
  5287. * @returns the current matrix
  5288. */
  5289. Matrix.prototype.multiplyToRef = function (other, result) {
  5290. this.multiplyToArray(other, result.m, 0);
  5291. result._markAsUpdated();
  5292. return this;
  5293. };
  5294. /**
  5295. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5296. * @param other defines the second operand
  5297. * @param result defines the array where to store the multiplication
  5298. * @param offset defines the offset in the target array where to start storing values
  5299. * @returns the current matrix
  5300. */
  5301. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5302. var tm0 = this.m[0];
  5303. var tm1 = this.m[1];
  5304. var tm2 = this.m[2];
  5305. var tm3 = this.m[3];
  5306. var tm4 = this.m[4];
  5307. var tm5 = this.m[5];
  5308. var tm6 = this.m[6];
  5309. var tm7 = this.m[7];
  5310. var tm8 = this.m[8];
  5311. var tm9 = this.m[9];
  5312. var tm10 = this.m[10];
  5313. var tm11 = this.m[11];
  5314. var tm12 = this.m[12];
  5315. var tm13 = this.m[13];
  5316. var tm14 = this.m[14];
  5317. var tm15 = this.m[15];
  5318. var om0 = other.m[0];
  5319. var om1 = other.m[1];
  5320. var om2 = other.m[2];
  5321. var om3 = other.m[3];
  5322. var om4 = other.m[4];
  5323. var om5 = other.m[5];
  5324. var om6 = other.m[6];
  5325. var om7 = other.m[7];
  5326. var om8 = other.m[8];
  5327. var om9 = other.m[9];
  5328. var om10 = other.m[10];
  5329. var om11 = other.m[11];
  5330. var om12 = other.m[12];
  5331. var om13 = other.m[13];
  5332. var om14 = other.m[14];
  5333. var om15 = other.m[15];
  5334. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5335. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5336. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5337. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5338. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5339. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5340. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5341. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5342. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5343. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5344. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5345. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5346. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5347. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5348. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5349. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5350. return this;
  5351. };
  5352. /**
  5353. * Check equality between this matrix and a second one
  5354. * @param value defines the second matrix to compare
  5355. * @returns true is the current matrix and the given one values are strictly equal
  5356. */
  5357. Matrix.prototype.equals = function (value) {
  5358. return value &&
  5359. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5360. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5361. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5362. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5363. };
  5364. /**
  5365. * Clone the current matrix
  5366. * @returns a new matrix from the current matrix
  5367. */
  5368. Matrix.prototype.clone = function () {
  5369. 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]);
  5370. };
  5371. /**
  5372. * Returns the name of the current matrix class
  5373. * @returns the string "Matrix"
  5374. */
  5375. Matrix.prototype.getClassName = function () {
  5376. return "Matrix";
  5377. };
  5378. /**
  5379. * Gets the hash code of the current matrix
  5380. * @returns the hash code
  5381. */
  5382. Matrix.prototype.getHashCode = function () {
  5383. var hash = this.m[0] || 0;
  5384. for (var i = 1; i < 16; i++) {
  5385. hash = (hash * 397) ^ (this.m[i] || 0);
  5386. }
  5387. return hash;
  5388. };
  5389. /**
  5390. * Decomposes the current Matrix into a translation, rotation and scaling components
  5391. * @param scale defines the scale vector3 given as a reference to update
  5392. * @param rotation defines the rotation quaternion given as a reference to update
  5393. * @param translation defines the translation vector3 given as a reference to update
  5394. * @returns true if operation was successful
  5395. */
  5396. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5397. if (translation) {
  5398. translation.x = this.m[12];
  5399. translation.y = this.m[13];
  5400. translation.z = this.m[14];
  5401. }
  5402. scale = scale || MathTmp.Vector3[0];
  5403. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5404. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5405. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5406. if (this.determinant() <= 0) {
  5407. scale.y *= -1;
  5408. }
  5409. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5410. if (rotation) {
  5411. rotation.x = 0;
  5412. rotation.y = 0;
  5413. rotation.z = 0;
  5414. rotation.w = 1;
  5415. }
  5416. return false;
  5417. }
  5418. if (rotation) {
  5419. 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]);
  5420. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5421. }
  5422. return true;
  5423. };
  5424. /**
  5425. * Gets specific row of the matrix
  5426. * @param index defines the number of the row to get
  5427. * @returns the index-th row of the current matrix as a new Vector4
  5428. */
  5429. Matrix.prototype.getRow = function (index) {
  5430. if (index < 0 || index > 3) {
  5431. return null;
  5432. }
  5433. var i = index * 4;
  5434. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5435. };
  5436. /**
  5437. * Sets the index-th row of the current matrix to the vector4 values
  5438. * @param index defines the number of the row to set
  5439. * @param row defines the target vector4
  5440. * @returns the updated current matrix
  5441. */
  5442. Matrix.prototype.setRow = function (index, row) {
  5443. if (index < 0 || index > 3) {
  5444. return this;
  5445. }
  5446. var i = index * 4;
  5447. this.m[i + 0] = row.x;
  5448. this.m[i + 1] = row.y;
  5449. this.m[i + 2] = row.z;
  5450. this.m[i + 3] = row.w;
  5451. this._markAsUpdated();
  5452. return this;
  5453. };
  5454. /**
  5455. * Compute the transpose of the matrix
  5456. * @returns the new transposed matrix
  5457. */
  5458. Matrix.prototype.transpose = function () {
  5459. return Matrix.Transpose(this);
  5460. };
  5461. /**
  5462. * Compute the transpose of the matrix and store it in a given matrix
  5463. * @param result defines the target matrix
  5464. * @returns the current matrix
  5465. */
  5466. Matrix.prototype.transposeToRef = function (result) {
  5467. Matrix.TransposeToRef(this, result);
  5468. return this;
  5469. };
  5470. /**
  5471. * Sets the index-th row of the current matrix with the given 4 x float values
  5472. * @param index defines the row index
  5473. * @param x defines the x component to set
  5474. * @param y defines the y component to set
  5475. * @param z defines the z component to set
  5476. * @param w defines the w component to set
  5477. * @returns the updated current matrix
  5478. */
  5479. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5480. if (index < 0 || index > 3) {
  5481. return this;
  5482. }
  5483. var i = index * 4;
  5484. this.m[i + 0] = x;
  5485. this.m[i + 1] = y;
  5486. this.m[i + 2] = z;
  5487. this.m[i + 3] = w;
  5488. this._markAsUpdated();
  5489. return this;
  5490. };
  5491. /**
  5492. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5493. * @param scale defines the scale factor
  5494. * @returns a new matrix
  5495. */
  5496. Matrix.prototype.scale = function (scale) {
  5497. var result = new Matrix();
  5498. this.scaleToRef(scale, result);
  5499. return result;
  5500. };
  5501. /**
  5502. * Scale the current matrix values by a factor to a given result matrix
  5503. * @param scale defines the scale factor
  5504. * @param result defines the matrix to store the result
  5505. * @returns the current matrix
  5506. */
  5507. Matrix.prototype.scaleToRef = function (scale, result) {
  5508. for (var index = 0; index < 16; index++) {
  5509. result.m[index] = this.m[index] * scale;
  5510. }
  5511. result._markAsUpdated();
  5512. return this;
  5513. };
  5514. /**
  5515. * Scale the current matrix values by a factor and add the result to a given matrix
  5516. * @param scale defines the scale factor
  5517. * @param result defines the Matrix to store the result
  5518. * @returns the current matrix
  5519. */
  5520. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5521. for (var index = 0; index < 16; index++) {
  5522. result.m[index] += this.m[index] * scale;
  5523. }
  5524. result._markAsUpdated();
  5525. return this;
  5526. };
  5527. /**
  5528. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5529. * @param ref matrix to store the result
  5530. */
  5531. Matrix.prototype.toNormalMatrix = function (ref) {
  5532. this.invertToRef(ref);
  5533. ref.transpose();
  5534. var m = ref.m;
  5535. 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);
  5536. };
  5537. /**
  5538. * Gets only rotation part of the current matrix
  5539. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5540. */
  5541. Matrix.prototype.getRotationMatrix = function () {
  5542. var result = Matrix.Identity();
  5543. this.getRotationMatrixToRef(result);
  5544. return result;
  5545. };
  5546. /**
  5547. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5548. * @param result defines the target matrix to store data to
  5549. * @returns the current matrix
  5550. */
  5551. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5552. var m = this.m;
  5553. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5554. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5555. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5556. if (this.determinant() <= 0) {
  5557. sy *= -1;
  5558. }
  5559. if (sx === 0 || sy === 0 || sz === 0) {
  5560. Matrix.IdentityToRef(result);
  5561. }
  5562. else {
  5563. 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);
  5564. }
  5565. return this;
  5566. };
  5567. // Statics
  5568. /**
  5569. * Creates a matrix from an array
  5570. * @param array defines the source array
  5571. * @param offset defines an offset in the source array
  5572. * @returns a new Matrix set from the starting index of the given array
  5573. */
  5574. Matrix.FromArray = function (array, offset) {
  5575. var result = new Matrix();
  5576. if (!offset) {
  5577. offset = 0;
  5578. }
  5579. Matrix.FromArrayToRef(array, offset, result);
  5580. return result;
  5581. };
  5582. /**
  5583. * Copy the content of an array into a given matrix
  5584. * @param array defines the source array
  5585. * @param offset defines an offset in the source array
  5586. * @param result defines the target matrix
  5587. */
  5588. Matrix.FromArrayToRef = function (array, offset, result) {
  5589. for (var index = 0; index < 16; index++) {
  5590. result.m[index] = array[index + offset];
  5591. }
  5592. result._markAsUpdated();
  5593. };
  5594. /**
  5595. * Stores an array into a matrix after having multiplied each component by a given factor
  5596. * @param array defines the source array
  5597. * @param offset defines the offset in the source array
  5598. * @param scale defines the scaling factor
  5599. * @param result defines the target matrix
  5600. */
  5601. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5602. for (var index = 0; index < 16; index++) {
  5603. result.m[index] = array[index + offset] * scale;
  5604. }
  5605. result._markAsUpdated();
  5606. };
  5607. /**
  5608. * Stores a list of values (16) inside a given matrix
  5609. * @param initialM11 defines 1st value of 1st row
  5610. * @param initialM12 defines 2nd value of 1st row
  5611. * @param initialM13 defines 3rd value of 1st row
  5612. * @param initialM14 defines 4th value of 1st row
  5613. * @param initialM21 defines 1st value of 2nd row
  5614. * @param initialM22 defines 2nd value of 2nd row
  5615. * @param initialM23 defines 3rd value of 2nd row
  5616. * @param initialM24 defines 4th value of 2nd row
  5617. * @param initialM31 defines 1st value of 3rd row
  5618. * @param initialM32 defines 2nd value of 3rd row
  5619. * @param initialM33 defines 3rd value of 3rd row
  5620. * @param initialM34 defines 4th value of 3rd row
  5621. * @param initialM41 defines 1st value of 4th row
  5622. * @param initialM42 defines 2nd value of 4th row
  5623. * @param initialM43 defines 3rd value of 4th row
  5624. * @param initialM44 defines 4th value of 4th row
  5625. * @param result defines the target matrix
  5626. */
  5627. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5628. result.m[0] = initialM11;
  5629. result.m[1] = initialM12;
  5630. result.m[2] = initialM13;
  5631. result.m[3] = initialM14;
  5632. result.m[4] = initialM21;
  5633. result.m[5] = initialM22;
  5634. result.m[6] = initialM23;
  5635. result.m[7] = initialM24;
  5636. result.m[8] = initialM31;
  5637. result.m[9] = initialM32;
  5638. result.m[10] = initialM33;
  5639. result.m[11] = initialM34;
  5640. result.m[12] = initialM41;
  5641. result.m[13] = initialM42;
  5642. result.m[14] = initialM43;
  5643. result.m[15] = initialM44;
  5644. result._markAsUpdated();
  5645. };
  5646. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5647. /**
  5648. * Gets an identity matrix that must not be updated
  5649. */
  5650. get: function () {
  5651. return Matrix._identityReadOnly;
  5652. },
  5653. enumerable: true,
  5654. configurable: true
  5655. });
  5656. /**
  5657. * Creates new matrix from a list of values (16)
  5658. * @param initialM11 defines 1st value of 1st row
  5659. * @param initialM12 defines 2nd value of 1st row
  5660. * @param initialM13 defines 3rd value of 1st row
  5661. * @param initialM14 defines 4th value of 1st row
  5662. * @param initialM21 defines 1st value of 2nd row
  5663. * @param initialM22 defines 2nd value of 2nd row
  5664. * @param initialM23 defines 3rd value of 2nd row
  5665. * @param initialM24 defines 4th value of 2nd row
  5666. * @param initialM31 defines 1st value of 3rd row
  5667. * @param initialM32 defines 2nd value of 3rd row
  5668. * @param initialM33 defines 3rd value of 3rd row
  5669. * @param initialM34 defines 4th value of 3rd row
  5670. * @param initialM41 defines 1st value of 4th row
  5671. * @param initialM42 defines 2nd value of 4th row
  5672. * @param initialM43 defines 3rd value of 4th row
  5673. * @param initialM44 defines 4th value of 4th row
  5674. * @returns the new matrix
  5675. */
  5676. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5677. var result = new Matrix();
  5678. result.m[0] = initialM11;
  5679. result.m[1] = initialM12;
  5680. result.m[2] = initialM13;
  5681. result.m[3] = initialM14;
  5682. result.m[4] = initialM21;
  5683. result.m[5] = initialM22;
  5684. result.m[6] = initialM23;
  5685. result.m[7] = initialM24;
  5686. result.m[8] = initialM31;
  5687. result.m[9] = initialM32;
  5688. result.m[10] = initialM33;
  5689. result.m[11] = initialM34;
  5690. result.m[12] = initialM41;
  5691. result.m[13] = initialM42;
  5692. result.m[14] = initialM43;
  5693. result.m[15] = initialM44;
  5694. return result;
  5695. };
  5696. /**
  5697. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5698. * @param scale defines the scale vector3
  5699. * @param rotation defines the rotation quaternion
  5700. * @param translation defines the translation vector3
  5701. * @returns a new matrix
  5702. */
  5703. Matrix.Compose = function (scale, rotation, translation) {
  5704. var result = Matrix.Identity();
  5705. Matrix.ComposeToRef(scale, rotation, translation, result);
  5706. return result;
  5707. };
  5708. /**
  5709. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5710. * @param scale defines the scale vector3
  5711. * @param rotation defines the rotation quaternion
  5712. * @param translation defines the translation vector3
  5713. * @param result defines the target matrix
  5714. */
  5715. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5716. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5717. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5718. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5719. result.setTranslation(translation);
  5720. };
  5721. /**
  5722. * Creates a new identity matrix
  5723. * @returns a new identity matrix
  5724. */
  5725. Matrix.Identity = function () {
  5726. 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);
  5727. };
  5728. /**
  5729. * Creates a new identity matrix and stores the result in a given matrix
  5730. * @param result defines the target matrix
  5731. */
  5732. Matrix.IdentityToRef = function (result) {
  5733. 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);
  5734. };
  5735. /**
  5736. * Creates a new zero matrix
  5737. * @returns a new zero matrix
  5738. */
  5739. Matrix.Zero = function () {
  5740. 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);
  5741. };
  5742. /**
  5743. * Creates a new rotation matrix for "angle" radians around the X axis
  5744. * @param angle defines the angle (in radians) to use
  5745. * @return the new matrix
  5746. */
  5747. Matrix.RotationX = function (angle) {
  5748. var result = new Matrix();
  5749. Matrix.RotationXToRef(angle, result);
  5750. return result;
  5751. };
  5752. /**
  5753. * Creates a new matrix as the invert of a given matrix
  5754. * @param source defines the source matrix
  5755. * @returns the new matrix
  5756. */
  5757. Matrix.Invert = function (source) {
  5758. var result = new Matrix();
  5759. source.invertToRef(result);
  5760. return result;
  5761. };
  5762. /**
  5763. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5764. * @param angle defines the angle (in radians) to use
  5765. * @param result defines the target matrix
  5766. */
  5767. Matrix.RotationXToRef = function (angle, result) {
  5768. var s = Math.sin(angle);
  5769. var c = Math.cos(angle);
  5770. result.m[0] = 1.0;
  5771. result.m[15] = 1.0;
  5772. result.m[5] = c;
  5773. result.m[10] = c;
  5774. result.m[9] = -s;
  5775. result.m[6] = s;
  5776. result.m[1] = 0.0;
  5777. result.m[2] = 0.0;
  5778. result.m[3] = 0.0;
  5779. result.m[4] = 0.0;
  5780. result.m[7] = 0.0;
  5781. result.m[8] = 0.0;
  5782. result.m[11] = 0.0;
  5783. result.m[12] = 0.0;
  5784. result.m[13] = 0.0;
  5785. result.m[14] = 0.0;
  5786. result._markAsUpdated();
  5787. };
  5788. /**
  5789. * Creates a new rotation matrix for "angle" radians around the Y axis
  5790. * @param angle defines the angle (in radians) to use
  5791. * @return the new matrix
  5792. */
  5793. Matrix.RotationY = function (angle) {
  5794. var result = new Matrix();
  5795. Matrix.RotationYToRef(angle, result);
  5796. return result;
  5797. };
  5798. /**
  5799. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5800. * @param angle defines the angle (in radians) to use
  5801. * @param result defines the target matrix
  5802. */
  5803. Matrix.RotationYToRef = function (angle, result) {
  5804. var s = Math.sin(angle);
  5805. var c = Math.cos(angle);
  5806. result.m[5] = 1.0;
  5807. result.m[15] = 1.0;
  5808. result.m[0] = c;
  5809. result.m[2] = -s;
  5810. result.m[8] = s;
  5811. result.m[10] = c;
  5812. result.m[1] = 0.0;
  5813. result.m[3] = 0.0;
  5814. result.m[4] = 0.0;
  5815. result.m[6] = 0.0;
  5816. result.m[7] = 0.0;
  5817. result.m[9] = 0.0;
  5818. result.m[11] = 0.0;
  5819. result.m[12] = 0.0;
  5820. result.m[13] = 0.0;
  5821. result.m[14] = 0.0;
  5822. result._markAsUpdated();
  5823. };
  5824. /**
  5825. * Creates a new rotation matrix for "angle" radians around the Z axis
  5826. * @param angle defines the angle (in radians) to use
  5827. * @return the new matrix
  5828. */
  5829. Matrix.RotationZ = function (angle) {
  5830. var result = new Matrix();
  5831. Matrix.RotationZToRef(angle, result);
  5832. return result;
  5833. };
  5834. /**
  5835. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5836. * @param angle defines the angle (in radians) to use
  5837. * @param result defines the target matrix
  5838. */
  5839. Matrix.RotationZToRef = function (angle, result) {
  5840. var s = Math.sin(angle);
  5841. var c = Math.cos(angle);
  5842. result.m[10] = 1.0;
  5843. result.m[15] = 1.0;
  5844. result.m[0] = c;
  5845. result.m[1] = s;
  5846. result.m[4] = -s;
  5847. result.m[5] = c;
  5848. result.m[2] = 0.0;
  5849. result.m[3] = 0.0;
  5850. result.m[6] = 0.0;
  5851. result.m[7] = 0.0;
  5852. result.m[8] = 0.0;
  5853. result.m[9] = 0.0;
  5854. result.m[11] = 0.0;
  5855. result.m[12] = 0.0;
  5856. result.m[13] = 0.0;
  5857. result.m[14] = 0.0;
  5858. result._markAsUpdated();
  5859. };
  5860. /**
  5861. * Creates a new rotation matrix for "angle" radians around the given axis
  5862. * @param axis defines the axis to use
  5863. * @param angle defines the angle (in radians) to use
  5864. * @return the new matrix
  5865. */
  5866. Matrix.RotationAxis = function (axis, angle) {
  5867. var result = Matrix.Zero();
  5868. Matrix.RotationAxisToRef(axis, angle, result);
  5869. return result;
  5870. };
  5871. /**
  5872. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5873. * @param axis defines the axis to use
  5874. * @param angle defines the angle (in radians) to use
  5875. * @param result defines the target matrix
  5876. */
  5877. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5878. var s = Math.sin(-angle);
  5879. var c = Math.cos(-angle);
  5880. var c1 = 1 - c;
  5881. axis.normalize();
  5882. result.m[0] = (axis.x * axis.x) * c1 + c;
  5883. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5884. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5885. result.m[3] = 0.0;
  5886. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5887. result.m[5] = (axis.y * axis.y) * c1 + c;
  5888. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5889. result.m[7] = 0.0;
  5890. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5891. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5892. result.m[10] = (axis.z * axis.z) * c1 + c;
  5893. result.m[11] = 0.0;
  5894. result.m[15] = 1.0;
  5895. result._markAsUpdated();
  5896. };
  5897. /**
  5898. * Creates a rotation matrix
  5899. * @param yaw defines the yaw angle in radians (Y axis)
  5900. * @param pitch defines the pitch angle in radians (X axis)
  5901. * @param roll defines the roll angle in radians (X axis)
  5902. * @returns the new rotation matrix
  5903. */
  5904. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5905. var result = new Matrix();
  5906. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5907. return result;
  5908. };
  5909. /**
  5910. * Creates a rotation matrix and stores it in a given matrix
  5911. * @param yaw defines the yaw angle in radians (Y axis)
  5912. * @param pitch defines the pitch angle in radians (X axis)
  5913. * @param roll defines the roll angle in radians (X axis)
  5914. * @param result defines the target matrix
  5915. */
  5916. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5917. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5918. this._tempQuaternion.toRotationMatrix(result);
  5919. };
  5920. /**
  5921. * Creates a scaling matrix
  5922. * @param x defines the scale factor on X axis
  5923. * @param y defines the scale factor on Y axis
  5924. * @param z defines the scale factor on Z axis
  5925. * @returns the new matrix
  5926. */
  5927. Matrix.Scaling = function (x, y, z) {
  5928. var result = Matrix.Zero();
  5929. Matrix.ScalingToRef(x, y, z, result);
  5930. return result;
  5931. };
  5932. /**
  5933. * Creates a scaling matrix and stores it in a given matrix
  5934. * @param x defines the scale factor on X axis
  5935. * @param y defines the scale factor on Y axis
  5936. * @param z defines the scale factor on Z axis
  5937. * @param result defines the target matrix
  5938. */
  5939. Matrix.ScalingToRef = function (x, y, z, result) {
  5940. result.m[0] = x;
  5941. result.m[1] = 0.0;
  5942. result.m[2] = 0.0;
  5943. result.m[3] = 0.0;
  5944. result.m[4] = 0.0;
  5945. result.m[5] = y;
  5946. result.m[6] = 0.0;
  5947. result.m[7] = 0.0;
  5948. result.m[8] = 0.0;
  5949. result.m[9] = 0.0;
  5950. result.m[10] = z;
  5951. result.m[11] = 0.0;
  5952. result.m[12] = 0.0;
  5953. result.m[13] = 0.0;
  5954. result.m[14] = 0.0;
  5955. result.m[15] = 1.0;
  5956. result._markAsUpdated();
  5957. };
  5958. /**
  5959. * Creates a translation matrix
  5960. * @param x defines the translation on X axis
  5961. * @param y defines the translation on Y axis
  5962. * @param z defines the translationon Z axis
  5963. * @returns the new matrix
  5964. */
  5965. Matrix.Translation = function (x, y, z) {
  5966. var result = Matrix.Identity();
  5967. Matrix.TranslationToRef(x, y, z, result);
  5968. return result;
  5969. };
  5970. /**
  5971. * Creates a translation matrix and stores it in a given matrix
  5972. * @param x defines the translation on X axis
  5973. * @param y defines the translation on Y axis
  5974. * @param z defines the translationon Z axis
  5975. * @param result defines the target matrix
  5976. */
  5977. Matrix.TranslationToRef = function (x, y, z, result) {
  5978. 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);
  5979. };
  5980. /**
  5981. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5982. * @param startValue defines the start value
  5983. * @param endValue defines the end value
  5984. * @param gradient defines the gradient factor
  5985. * @returns the new matrix
  5986. */
  5987. Matrix.Lerp = function (startValue, endValue, gradient) {
  5988. var result = Matrix.Zero();
  5989. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5990. return result;
  5991. };
  5992. /**
  5993. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5994. * @param startValue defines the start value
  5995. * @param endValue defines the end value
  5996. * @param gradient defines the gradient factor
  5997. * @param result defines the Matrix object where to store data
  5998. */
  5999. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6000. for (var index = 0; index < 16; index++) {
  6001. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6002. }
  6003. result._markAsUpdated();
  6004. };
  6005. /**
  6006. * Builds a new matrix whose values are computed by:
  6007. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6008. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6009. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6010. * @param startValue defines the first matrix
  6011. * @param endValue defines the second matrix
  6012. * @param gradient defines the gradient between the two matrices
  6013. * @returns the new matrix
  6014. */
  6015. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6016. var result = Matrix.Zero();
  6017. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6018. return result;
  6019. };
  6020. /**
  6021. * Update a matrix to values which are computed by:
  6022. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6023. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6024. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6025. * @param startValue defines the first matrix
  6026. * @param endValue defines the second matrix
  6027. * @param gradient defines the gradient between the two matrices
  6028. * @param result defines the target matrix
  6029. */
  6030. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6031. var startScale = MathTmp.Vector3[0];
  6032. var startRotation = MathTmp.Quaternion[0];
  6033. var startTranslation = MathTmp.Vector3[1];
  6034. startValue.decompose(startScale, startRotation, startTranslation);
  6035. var endScale = MathTmp.Vector3[2];
  6036. var endRotation = MathTmp.Quaternion[1];
  6037. var endTranslation = MathTmp.Vector3[3];
  6038. endValue.decompose(endScale, endRotation, endTranslation);
  6039. var resultScale = MathTmp.Vector3[4];
  6040. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6041. var resultRotation = MathTmp.Quaternion[2];
  6042. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6043. var resultTranslation = MathTmp.Vector3[5];
  6044. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6045. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6046. };
  6047. /**
  6048. * 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"
  6049. * This function works in left handed mode
  6050. * @param eye defines the final position of the entity
  6051. * @param target defines where the entity should look at
  6052. * @param up defines the up vector for the entity
  6053. * @returns the new matrix
  6054. */
  6055. Matrix.LookAtLH = function (eye, target, up) {
  6056. var result = Matrix.Zero();
  6057. Matrix.LookAtLHToRef(eye, target, up, result);
  6058. return result;
  6059. };
  6060. /**
  6061. * 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".
  6062. * This function works in left handed mode
  6063. * @param eye defines the final position of the entity
  6064. * @param target defines where the entity should look at
  6065. * @param up defines the up vector for the entity
  6066. * @param result defines the target matrix
  6067. */
  6068. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6069. // Z axis
  6070. target.subtractToRef(eye, this._zAxis);
  6071. this._zAxis.normalize();
  6072. // X axis
  6073. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6074. if (this._xAxis.lengthSquared() === 0) {
  6075. this._xAxis.x = 1.0;
  6076. }
  6077. else {
  6078. this._xAxis.normalize();
  6079. }
  6080. // Y axis
  6081. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6082. this._yAxis.normalize();
  6083. // Eye angles
  6084. var ex = -Vector3.Dot(this._xAxis, eye);
  6085. var ey = -Vector3.Dot(this._yAxis, eye);
  6086. var ez = -Vector3.Dot(this._zAxis, eye);
  6087. 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);
  6088. };
  6089. /**
  6090. * 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"
  6091. * This function works in right handed mode
  6092. * @param eye defines the final position of the entity
  6093. * @param target defines where the entity should look at
  6094. * @param up defines the up vector for the entity
  6095. * @returns the new matrix
  6096. */
  6097. Matrix.LookAtRH = function (eye, target, up) {
  6098. var result = Matrix.Zero();
  6099. Matrix.LookAtRHToRef(eye, target, up, result);
  6100. return result;
  6101. };
  6102. /**
  6103. * 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".
  6104. * This function works in right handed mode
  6105. * @param eye defines the final position of the entity
  6106. * @param target defines where the entity should look at
  6107. * @param up defines the up vector for the entity
  6108. * @param result defines the target matrix
  6109. */
  6110. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6111. // Z axis
  6112. eye.subtractToRef(target, this._zAxis);
  6113. this._zAxis.normalize();
  6114. // X axis
  6115. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6116. if (this._xAxis.lengthSquared() === 0) {
  6117. this._xAxis.x = 1.0;
  6118. }
  6119. else {
  6120. this._xAxis.normalize();
  6121. }
  6122. // Y axis
  6123. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6124. this._yAxis.normalize();
  6125. // Eye angles
  6126. var ex = -Vector3.Dot(this._xAxis, eye);
  6127. var ey = -Vector3.Dot(this._yAxis, eye);
  6128. var ez = -Vector3.Dot(this._zAxis, eye);
  6129. 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);
  6130. };
  6131. /**
  6132. * Create a left-handed orthographic projection matrix
  6133. * @param width defines the viewport width
  6134. * @param height defines the viewport height
  6135. * @param znear defines the near clip plane
  6136. * @param zfar defines the far clip plane
  6137. * @returns a new matrix as a left-handed orthographic projection matrix
  6138. */
  6139. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6140. var matrix = Matrix.Zero();
  6141. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6142. return matrix;
  6143. };
  6144. /**
  6145. * Store a left-handed orthographic projection to a given matrix
  6146. * @param width defines the viewport width
  6147. * @param height defines the viewport height
  6148. * @param znear defines the near clip plane
  6149. * @param zfar defines the far clip plane
  6150. * @param result defines the target matrix
  6151. */
  6152. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6153. var n = znear;
  6154. var f = zfar;
  6155. var a = 2.0 / width;
  6156. var b = 2.0 / height;
  6157. var c = 2.0 / (f - n);
  6158. var d = -(f + n) / (f - n);
  6159. 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);
  6160. };
  6161. /**
  6162. * Create a left-handed orthographic projection matrix
  6163. * @param left defines the viewport left coordinate
  6164. * @param right defines the viewport right coordinate
  6165. * @param bottom defines the viewport bottom coordinate
  6166. * @param top defines the viewport top coordinate
  6167. * @param znear defines the near clip plane
  6168. * @param zfar defines the far clip plane
  6169. * @returns a new matrix as a left-handed orthographic projection matrix
  6170. */
  6171. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6172. var matrix = Matrix.Zero();
  6173. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6174. return matrix;
  6175. };
  6176. /**
  6177. * Stores a left-handed orthographic projection into a given matrix
  6178. * @param left defines the viewport left coordinate
  6179. * @param right defines the viewport right coordinate
  6180. * @param bottom defines the viewport bottom coordinate
  6181. * @param top defines the viewport top coordinate
  6182. * @param znear defines the near clip plane
  6183. * @param zfar defines the far clip plane
  6184. * @param result defines the target matrix
  6185. */
  6186. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6187. var n = znear;
  6188. var f = zfar;
  6189. var a = 2.0 / (right - left);
  6190. var b = 2.0 / (top - bottom);
  6191. var c = 2.0 / (f - n);
  6192. var d = -(f + n) / (f - n);
  6193. var i0 = (left + right) / (left - right);
  6194. var i1 = (top + bottom) / (bottom - top);
  6195. 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);
  6196. };
  6197. /**
  6198. * Creates a right-handed orthographic projection matrix
  6199. * @param left defines the viewport left coordinate
  6200. * @param right defines the viewport right coordinate
  6201. * @param bottom defines the viewport bottom coordinate
  6202. * @param top defines the viewport top coordinate
  6203. * @param znear defines the near clip plane
  6204. * @param zfar defines the far clip plane
  6205. * @returns a new matrix as a right-handed orthographic projection matrix
  6206. */
  6207. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6208. var matrix = Matrix.Zero();
  6209. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6210. return matrix;
  6211. };
  6212. /**
  6213. * Stores a right-handed orthographic projection into a given matrix
  6214. * @param left defines the viewport left coordinate
  6215. * @param right defines the viewport right coordinate
  6216. * @param bottom defines the viewport bottom coordinate
  6217. * @param top defines the viewport top coordinate
  6218. * @param znear defines the near clip plane
  6219. * @param zfar defines the far clip plane
  6220. * @param result defines the target matrix
  6221. */
  6222. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6223. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6224. result.m[10] *= -1.0;
  6225. };
  6226. /**
  6227. * Creates a left-handed perspective projection matrix
  6228. * @param width defines the viewport width
  6229. * @param height defines the viewport height
  6230. * @param znear defines the near clip plane
  6231. * @param zfar defines the far clip plane
  6232. * @returns a new matrix as a left-handed perspective projection matrix
  6233. */
  6234. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6235. var matrix = Matrix.Zero();
  6236. var n = znear;
  6237. var f = zfar;
  6238. var a = 2.0 * n / width;
  6239. var b = 2.0 * n / height;
  6240. var c = (f + n) / (f - n);
  6241. var d = -2.0 * f * n / (f - n);
  6242. 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);
  6243. return matrix;
  6244. };
  6245. /**
  6246. * Creates a left-handed perspective projection matrix
  6247. * @param fov defines the horizontal field of view
  6248. * @param aspect defines the aspect ratio
  6249. * @param znear defines the near clip plane
  6250. * @param zfar defines the far clip plane
  6251. * @returns a new matrix as a left-handed perspective projection matrix
  6252. */
  6253. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6254. var matrix = Matrix.Zero();
  6255. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6256. return matrix;
  6257. };
  6258. /**
  6259. * Stores a left-handed perspective projection into a given matrix
  6260. * @param fov defines the horizontal field of view
  6261. * @param aspect defines the aspect ratio
  6262. * @param znear defines the near clip plane
  6263. * @param zfar defines the far clip plane
  6264. * @param result defines the target matrix
  6265. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6266. */
  6267. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6268. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6269. var n = znear;
  6270. var f = zfar;
  6271. var t = 1.0 / (Math.tan(fov * 0.5));
  6272. var a = isVerticalFovFixed ? (t / aspect) : t;
  6273. var b = isVerticalFovFixed ? t : (t * aspect);
  6274. var c = (f + n) / (f - n);
  6275. var d = -2.0 * f * n / (f - n);
  6276. 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);
  6277. };
  6278. /**
  6279. * Creates a right-handed perspective projection matrix
  6280. * @param fov defines the horizontal field of view
  6281. * @param aspect defines the aspect ratio
  6282. * @param znear defines the near clip plane
  6283. * @param zfar defines the far clip plane
  6284. * @returns a new matrix as a right-handed perspective projection matrix
  6285. */
  6286. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6287. var matrix = Matrix.Zero();
  6288. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6289. return matrix;
  6290. };
  6291. /**
  6292. * Stores a right-handed perspective projection into a given matrix
  6293. * @param fov defines the horizontal field of view
  6294. * @param aspect defines the aspect ratio
  6295. * @param znear defines the near clip plane
  6296. * @param zfar defines the far clip plane
  6297. * @param result defines the target matrix
  6298. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6299. */
  6300. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6301. //alternatively this could be expressed as:
  6302. // m = PerspectiveFovLHToRef
  6303. // m[10] *= -1.0;
  6304. // m[11] *= -1.0;
  6305. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6306. var n = znear;
  6307. var f = zfar;
  6308. var t = 1.0 / (Math.tan(fov * 0.5));
  6309. var a = isVerticalFovFixed ? (t / aspect) : t;
  6310. var b = isVerticalFovFixed ? t : (t * aspect);
  6311. var c = -(f + n) / (f - n);
  6312. var d = -2 * f * n / (f - n);
  6313. 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);
  6314. };
  6315. /**
  6316. * Stores a perspective projection for WebVR info a given matrix
  6317. * @param fov defines the field of view
  6318. * @param znear defines the near clip plane
  6319. * @param zfar defines the far clip plane
  6320. * @param result defines the target matrix
  6321. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6322. */
  6323. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6324. if (rightHanded === void 0) { rightHanded = false; }
  6325. var rightHandedFactor = rightHanded ? -1 : 1;
  6326. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6327. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6328. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6329. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6330. var xScale = 2.0 / (leftTan + rightTan);
  6331. var yScale = 2.0 / (upTan + downTan);
  6332. result.m[0] = xScale;
  6333. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6334. result.m[5] = yScale;
  6335. result.m[6] = result.m[7] = 0.0;
  6336. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6337. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6338. result.m[10] = -zfar / (znear - zfar);
  6339. result.m[11] = 1.0 * rightHandedFactor;
  6340. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6341. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6342. result._markAsUpdated();
  6343. };
  6344. /**
  6345. * Computes a complete transformation matrix
  6346. * @param viewport defines the viewport to use
  6347. * @param world defines the world matrix
  6348. * @param view defines the view matrix
  6349. * @param projection defines the projection matrix
  6350. * @param zmin defines the near clip plane
  6351. * @param zmax defines the far clip plane
  6352. * @returns the transformation matrix
  6353. */
  6354. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6355. var cw = viewport.width;
  6356. var ch = viewport.height;
  6357. var cx = viewport.x;
  6358. var cy = viewport.y;
  6359. 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);
  6360. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6361. };
  6362. /**
  6363. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6364. * @param matrix defines the matrix to use
  6365. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6366. */
  6367. Matrix.GetAsMatrix2x2 = function (matrix) {
  6368. return new Float32Array([
  6369. matrix.m[0], matrix.m[1],
  6370. matrix.m[4], matrix.m[5]
  6371. ]);
  6372. };
  6373. /**
  6374. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6375. * @param matrix defines the matrix to use
  6376. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6377. */
  6378. Matrix.GetAsMatrix3x3 = function (matrix) {
  6379. return new Float32Array([
  6380. matrix.m[0], matrix.m[1], matrix.m[2],
  6381. matrix.m[4], matrix.m[5], matrix.m[6],
  6382. matrix.m[8], matrix.m[9], matrix.m[10]
  6383. ]);
  6384. };
  6385. /**
  6386. * Compute the transpose of a given matrix
  6387. * @param matrix defines the matrix to transpose
  6388. * @returns the new matrix
  6389. */
  6390. Matrix.Transpose = function (matrix) {
  6391. var result = new Matrix();
  6392. Matrix.TransposeToRef(matrix, result);
  6393. return result;
  6394. };
  6395. /**
  6396. * Compute the transpose of a matrix and store it in a target matrix
  6397. * @param matrix defines the matrix to transpose
  6398. * @param result defines the target matrix
  6399. */
  6400. Matrix.TransposeToRef = function (matrix, result) {
  6401. result.m[0] = matrix.m[0];
  6402. result.m[1] = matrix.m[4];
  6403. result.m[2] = matrix.m[8];
  6404. result.m[3] = matrix.m[12];
  6405. result.m[4] = matrix.m[1];
  6406. result.m[5] = matrix.m[5];
  6407. result.m[6] = matrix.m[9];
  6408. result.m[7] = matrix.m[13];
  6409. result.m[8] = matrix.m[2];
  6410. result.m[9] = matrix.m[6];
  6411. result.m[10] = matrix.m[10];
  6412. result.m[11] = matrix.m[14];
  6413. result.m[12] = matrix.m[3];
  6414. result.m[13] = matrix.m[7];
  6415. result.m[14] = matrix.m[11];
  6416. result.m[15] = matrix.m[15];
  6417. };
  6418. /**
  6419. * Computes a reflection matrix from a plane
  6420. * @param plane defines the reflection plane
  6421. * @returns a new matrix
  6422. */
  6423. Matrix.Reflection = function (plane) {
  6424. var matrix = new Matrix();
  6425. Matrix.ReflectionToRef(plane, matrix);
  6426. return matrix;
  6427. };
  6428. /**
  6429. * Computes a reflection matrix from a plane
  6430. * @param plane defines the reflection plane
  6431. * @param result defines the target matrix
  6432. */
  6433. Matrix.ReflectionToRef = function (plane, result) {
  6434. plane.normalize();
  6435. var x = plane.normal.x;
  6436. var y = plane.normal.y;
  6437. var z = plane.normal.z;
  6438. var temp = -2 * x;
  6439. var temp2 = -2 * y;
  6440. var temp3 = -2 * z;
  6441. result.m[0] = (temp * x) + 1;
  6442. result.m[1] = temp2 * x;
  6443. result.m[2] = temp3 * x;
  6444. result.m[3] = 0.0;
  6445. result.m[4] = temp * y;
  6446. result.m[5] = (temp2 * y) + 1;
  6447. result.m[6] = temp3 * y;
  6448. result.m[7] = 0.0;
  6449. result.m[8] = temp * z;
  6450. result.m[9] = temp2 * z;
  6451. result.m[10] = (temp3 * z) + 1;
  6452. result.m[11] = 0.0;
  6453. result.m[12] = temp * plane.d;
  6454. result.m[13] = temp2 * plane.d;
  6455. result.m[14] = temp3 * plane.d;
  6456. result.m[15] = 1.0;
  6457. result._markAsUpdated();
  6458. };
  6459. /**
  6460. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6461. * @param xaxis defines the value of the 1st axis
  6462. * @param yaxis defines the value of the 2nd axis
  6463. * @param zaxis defines the value of the 3rd axis
  6464. * @param result defines the target matrix
  6465. */
  6466. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6467. result.m[0] = xaxis.x;
  6468. result.m[1] = xaxis.y;
  6469. result.m[2] = xaxis.z;
  6470. result.m[3] = 0.0;
  6471. result.m[4] = yaxis.x;
  6472. result.m[5] = yaxis.y;
  6473. result.m[6] = yaxis.z;
  6474. result.m[7] = 0.0;
  6475. result.m[8] = zaxis.x;
  6476. result.m[9] = zaxis.y;
  6477. result.m[10] = zaxis.z;
  6478. result.m[11] = 0.0;
  6479. result.m[12] = 0.0;
  6480. result.m[13] = 0.0;
  6481. result.m[14] = 0.0;
  6482. result.m[15] = 1.0;
  6483. result._markAsUpdated();
  6484. };
  6485. /**
  6486. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6487. * @param quat defines the quaternion to use
  6488. * @param result defines the target matrix
  6489. */
  6490. Matrix.FromQuaternionToRef = function (quat, result) {
  6491. var xx = quat.x * quat.x;
  6492. var yy = quat.y * quat.y;
  6493. var zz = quat.z * quat.z;
  6494. var xy = quat.x * quat.y;
  6495. var zw = quat.z * quat.w;
  6496. var zx = quat.z * quat.x;
  6497. var yw = quat.y * quat.w;
  6498. var yz = quat.y * quat.z;
  6499. var xw = quat.x * quat.w;
  6500. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6501. result.m[1] = 2.0 * (xy + zw);
  6502. result.m[2] = 2.0 * (zx - yw);
  6503. result.m[3] = 0.0;
  6504. result.m[4] = 2.0 * (xy - zw);
  6505. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6506. result.m[6] = 2.0 * (yz + xw);
  6507. result.m[7] = 0.0;
  6508. result.m[8] = 2.0 * (zx + yw);
  6509. result.m[9] = 2.0 * (yz - xw);
  6510. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6511. result.m[11] = 0.0;
  6512. result.m[12] = 0.0;
  6513. result.m[13] = 0.0;
  6514. result.m[14] = 0.0;
  6515. result.m[15] = 1.0;
  6516. result._markAsUpdated();
  6517. };
  6518. Matrix._tempQuaternion = new Quaternion();
  6519. Matrix._xAxis = Vector3.Zero();
  6520. Matrix._yAxis = Vector3.Zero();
  6521. Matrix._zAxis = Vector3.Zero();
  6522. Matrix._updateFlagSeed = 0;
  6523. Matrix._identityReadOnly = Matrix.Identity();
  6524. return Matrix;
  6525. }());
  6526. BABYLON.Matrix = Matrix;
  6527. var Plane = /** @class */ (function () {
  6528. /**
  6529. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6530. */
  6531. function Plane(a, b, c, d) {
  6532. this.normal = new Vector3(a, b, c);
  6533. this.d = d;
  6534. }
  6535. /**
  6536. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6537. */
  6538. Plane.prototype.asArray = function () {
  6539. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6540. };
  6541. // Methods
  6542. /**
  6543. * Returns a new plane copied from the current Plane.
  6544. */
  6545. Plane.prototype.clone = function () {
  6546. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6547. };
  6548. /**
  6549. * Returns the string "Plane".
  6550. */
  6551. Plane.prototype.getClassName = function () {
  6552. return "Plane";
  6553. };
  6554. /**
  6555. * Returns the Plane hash code.
  6556. */
  6557. Plane.prototype.getHashCode = function () {
  6558. var hash = this.normal.getHashCode();
  6559. hash = (hash * 397) ^ (this.d || 0);
  6560. return hash;
  6561. };
  6562. /**
  6563. * Normalize the current Plane in place.
  6564. * Returns the updated Plane.
  6565. */
  6566. Plane.prototype.normalize = function () {
  6567. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6568. var magnitude = 0.0;
  6569. if (norm !== 0) {
  6570. magnitude = 1.0 / norm;
  6571. }
  6572. this.normal.x *= magnitude;
  6573. this.normal.y *= magnitude;
  6574. this.normal.z *= magnitude;
  6575. this.d *= magnitude;
  6576. return this;
  6577. };
  6578. /**
  6579. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6580. */
  6581. Plane.prototype.transform = function (transformation) {
  6582. var transposedMatrix = Matrix.Transpose(transformation);
  6583. var x = this.normal.x;
  6584. var y = this.normal.y;
  6585. var z = this.normal.z;
  6586. var d = this.d;
  6587. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6588. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6589. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6590. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6591. return new Plane(normalX, normalY, normalZ, finalD);
  6592. };
  6593. /**
  6594. * Returns the dot product (float) of the point coordinates and the plane normal.
  6595. */
  6596. Plane.prototype.dotCoordinate = function (point) {
  6597. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6598. };
  6599. /**
  6600. * Updates the current Plane from the plane defined by the three given points.
  6601. * Returns the updated Plane.
  6602. */
  6603. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6604. var x1 = point2.x - point1.x;
  6605. var y1 = point2.y - point1.y;
  6606. var z1 = point2.z - point1.z;
  6607. var x2 = point3.x - point1.x;
  6608. var y2 = point3.y - point1.y;
  6609. var z2 = point3.z - point1.z;
  6610. var yz = (y1 * z2) - (z1 * y2);
  6611. var xz = (z1 * x2) - (x1 * z2);
  6612. var xy = (x1 * y2) - (y1 * x2);
  6613. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6614. var invPyth;
  6615. if (pyth !== 0) {
  6616. invPyth = 1.0 / pyth;
  6617. }
  6618. else {
  6619. invPyth = 0.0;
  6620. }
  6621. this.normal.x = yz * invPyth;
  6622. this.normal.y = xz * invPyth;
  6623. this.normal.z = xy * invPyth;
  6624. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6625. return this;
  6626. };
  6627. /**
  6628. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6629. */
  6630. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6631. var dot = Vector3.Dot(this.normal, direction);
  6632. return (dot <= epsilon);
  6633. };
  6634. /**
  6635. * Returns the signed distance (float) from the given point to the Plane.
  6636. */
  6637. Plane.prototype.signedDistanceTo = function (point) {
  6638. return Vector3.Dot(point, this.normal) + this.d;
  6639. };
  6640. // Statics
  6641. /**
  6642. * Returns a new Plane from the given array.
  6643. */
  6644. Plane.FromArray = function (array) {
  6645. return new Plane(array[0], array[1], array[2], array[3]);
  6646. };
  6647. /**
  6648. * Returns a new Plane defined by the three given points.
  6649. */
  6650. Plane.FromPoints = function (point1, point2, point3) {
  6651. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6652. result.copyFromPoints(point1, point2, point3);
  6653. return result;
  6654. };
  6655. /**
  6656. * Returns a new Plane the normal vector to this plane at the given origin point.
  6657. * Note : the vector "normal" is updated because normalized.
  6658. */
  6659. Plane.FromPositionAndNormal = function (origin, normal) {
  6660. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6661. normal.normalize();
  6662. result.normal = normal;
  6663. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6664. return result;
  6665. };
  6666. /**
  6667. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6668. */
  6669. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6670. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6671. return Vector3.Dot(point, normal) + d;
  6672. };
  6673. return Plane;
  6674. }());
  6675. BABYLON.Plane = Plane;
  6676. var Viewport = /** @class */ (function () {
  6677. /**
  6678. * Creates a Viewport object located at (x, y) and sized (width, height).
  6679. */
  6680. function Viewport(x, y, width, height) {
  6681. this.x = x;
  6682. this.y = y;
  6683. this.width = width;
  6684. this.height = height;
  6685. }
  6686. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6687. if (renderWidthOrEngine.getRenderWidth) {
  6688. var engine = renderWidthOrEngine;
  6689. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6690. }
  6691. var renderWidth = renderWidthOrEngine;
  6692. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6693. };
  6694. /**
  6695. * Returns a new Viewport copied from the current one.
  6696. */
  6697. Viewport.prototype.clone = function () {
  6698. return new Viewport(this.x, this.y, this.width, this.height);
  6699. };
  6700. return Viewport;
  6701. }());
  6702. BABYLON.Viewport = Viewport;
  6703. var Frustum = /** @class */ (function () {
  6704. function Frustum() {
  6705. }
  6706. /**
  6707. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6708. */
  6709. Frustum.GetPlanes = function (transform) {
  6710. var frustumPlanes = [];
  6711. for (var index = 0; index < 6; index++) {
  6712. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6713. }
  6714. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6715. return frustumPlanes;
  6716. };
  6717. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6718. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6719. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6720. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6721. frustumPlane.d = transform.m[15] + transform.m[14];
  6722. frustumPlane.normalize();
  6723. };
  6724. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6725. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6726. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6727. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6728. frustumPlane.d = transform.m[15] - transform.m[14];
  6729. frustumPlane.normalize();
  6730. };
  6731. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6732. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6733. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6734. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6735. frustumPlane.d = transform.m[15] + transform.m[12];
  6736. frustumPlane.normalize();
  6737. };
  6738. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6739. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6740. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6741. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6742. frustumPlane.d = transform.m[15] - transform.m[12];
  6743. frustumPlane.normalize();
  6744. };
  6745. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6746. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6747. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6748. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6749. frustumPlane.d = transform.m[15] - transform.m[13];
  6750. frustumPlane.normalize();
  6751. };
  6752. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6753. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6754. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6755. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6756. frustumPlane.d = transform.m[15] + transform.m[13];
  6757. frustumPlane.normalize();
  6758. };
  6759. /**
  6760. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6761. */
  6762. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6763. // Near
  6764. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6765. // Far
  6766. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6767. // Left
  6768. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6769. // Right
  6770. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6771. // Top
  6772. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6773. // Bottom
  6774. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6775. };
  6776. return Frustum;
  6777. }());
  6778. BABYLON.Frustum = Frustum;
  6779. /** Defines supported spaces */
  6780. var Space;
  6781. (function (Space) {
  6782. /** Local (object) space */
  6783. Space[Space["LOCAL"] = 0] = "LOCAL";
  6784. /** World space */
  6785. Space[Space["WORLD"] = 1] = "WORLD";
  6786. /** Bone space */
  6787. Space[Space["BONE"] = 2] = "BONE";
  6788. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6789. /** Defines the 3 main axes */
  6790. var Axis = /** @class */ (function () {
  6791. function Axis() {
  6792. }
  6793. /** X axis */
  6794. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6795. /** Y axis */
  6796. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6797. /** Z axis */
  6798. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6799. return Axis;
  6800. }());
  6801. BABYLON.Axis = Axis;
  6802. ;
  6803. var BezierCurve = /** @class */ (function () {
  6804. function BezierCurve() {
  6805. }
  6806. /**
  6807. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6808. */
  6809. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6810. // Extract X (which is equal to time here)
  6811. var f0 = 1 - 3 * x2 + 3 * x1;
  6812. var f1 = 3 * x2 - 6 * x1;
  6813. var f2 = 3 * x1;
  6814. var refinedT = t;
  6815. for (var i = 0; i < 5; i++) {
  6816. var refinedT2 = refinedT * refinedT;
  6817. var refinedT3 = refinedT2 * refinedT;
  6818. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6819. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6820. refinedT -= (x - t) * slope;
  6821. refinedT = Math.min(1, Math.max(0, refinedT));
  6822. }
  6823. // Resolve cubic bezier for the given x
  6824. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6825. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6826. Math.pow(refinedT, 3);
  6827. };
  6828. return BezierCurve;
  6829. }());
  6830. BABYLON.BezierCurve = BezierCurve;
  6831. /**
  6832. * Defines potential orientation for back face culling
  6833. */
  6834. var Orientation;
  6835. (function (Orientation) {
  6836. /**
  6837. * Clockwise
  6838. */
  6839. Orientation[Orientation["CW"] = 0] = "CW";
  6840. /** Counter clockwise */
  6841. Orientation[Orientation["CCW"] = 1] = "CCW";
  6842. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6843. /**
  6844. * Defines angle representation
  6845. */
  6846. var Angle = /** @class */ (function () {
  6847. /**
  6848. * Creates an Angle object of "radians" radians (float).
  6849. */
  6850. function Angle(radians) {
  6851. this._radians = radians;
  6852. if (this._radians < 0.0)
  6853. this._radians += (2.0 * Math.PI);
  6854. }
  6855. /**
  6856. * Get value in degrees
  6857. * @returns the Angle value in degrees (float)
  6858. */
  6859. Angle.prototype.degrees = function () {
  6860. return this._radians * 180.0 / Math.PI;
  6861. };
  6862. /**
  6863. * Get value in radians
  6864. * @returns the Angle value in radians (float)
  6865. */
  6866. Angle.prototype.radians = function () {
  6867. return this._radians;
  6868. };
  6869. /**
  6870. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6871. * @param a defines first vector
  6872. * @param b defines second vector
  6873. * @returns a new Angle
  6874. */
  6875. Angle.BetweenTwoPoints = function (a, b) {
  6876. var delta = b.subtract(a);
  6877. var theta = Math.atan2(delta.y, delta.x);
  6878. return new Angle(theta);
  6879. };
  6880. /**
  6881. * Gets a new Angle object from the given float in radians
  6882. * @param radians defines the angle value in radians
  6883. * @returns a new Angle
  6884. */
  6885. Angle.FromRadians = function (radians) {
  6886. return new Angle(radians);
  6887. };
  6888. /**
  6889. * Gets a new Angle object from the given float in degrees
  6890. * @param degrees defines the angle value in degrees
  6891. * @returns a new Angle
  6892. */
  6893. Angle.FromDegrees = function (degrees) {
  6894. return new Angle(degrees * Math.PI / 180.0);
  6895. };
  6896. return Angle;
  6897. }());
  6898. BABYLON.Angle = Angle;
  6899. var Arc2 = /** @class */ (function () {
  6900. /**
  6901. * Creates an Arc object from the three given points : start, middle and end.
  6902. */
  6903. function Arc2(startPoint, midPoint, endPoint) {
  6904. this.startPoint = startPoint;
  6905. this.midPoint = midPoint;
  6906. this.endPoint = endPoint;
  6907. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6908. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6909. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6910. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6911. 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);
  6912. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6913. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6914. var a1 = this.startAngle.degrees();
  6915. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6916. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6917. // angles correction
  6918. if (a2 - a1 > +180.0)
  6919. a2 -= 360.0;
  6920. if (a2 - a1 < -180.0)
  6921. a2 += 360.0;
  6922. if (a3 - a2 > +180.0)
  6923. a3 -= 360.0;
  6924. if (a3 - a2 < -180.0)
  6925. a3 += 360.0;
  6926. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6927. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6928. }
  6929. return Arc2;
  6930. }());
  6931. BABYLON.Arc2 = Arc2;
  6932. var Path2 = /** @class */ (function () {
  6933. /**
  6934. * Creates a Path2 object from the starting 2D coordinates x and y.
  6935. */
  6936. function Path2(x, y) {
  6937. this._points = new Array();
  6938. this._length = 0.0;
  6939. this.closed = false;
  6940. this._points.push(new Vector2(x, y));
  6941. }
  6942. /**
  6943. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6944. * Returns the updated Path2.
  6945. */
  6946. Path2.prototype.addLineTo = function (x, y) {
  6947. if (this.closed) {
  6948. return this;
  6949. }
  6950. var newPoint = new Vector2(x, y);
  6951. var previousPoint = this._points[this._points.length - 1];
  6952. this._points.push(newPoint);
  6953. this._length += newPoint.subtract(previousPoint).length();
  6954. return this;
  6955. };
  6956. /**
  6957. * 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.
  6958. * Returns the updated Path2.
  6959. */
  6960. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6961. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6962. if (this.closed) {
  6963. return this;
  6964. }
  6965. var startPoint = this._points[this._points.length - 1];
  6966. var midPoint = new Vector2(midX, midY);
  6967. var endPoint = new Vector2(endX, endY);
  6968. var arc = new Arc2(startPoint, midPoint, endPoint);
  6969. var increment = arc.angle.radians() / numberOfSegments;
  6970. if (arc.orientation === Orientation.CW)
  6971. increment *= -1;
  6972. var currentAngle = arc.startAngle.radians() + increment;
  6973. for (var i = 0; i < numberOfSegments; i++) {
  6974. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6975. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6976. this.addLineTo(x, y);
  6977. currentAngle += increment;
  6978. }
  6979. return this;
  6980. };
  6981. /**
  6982. * Closes the Path2.
  6983. * Returns the Path2.
  6984. */
  6985. Path2.prototype.close = function () {
  6986. this.closed = true;
  6987. return this;
  6988. };
  6989. /**
  6990. * Returns the Path2 total length (float).
  6991. */
  6992. Path2.prototype.length = function () {
  6993. var result = this._length;
  6994. if (!this.closed) {
  6995. var lastPoint = this._points[this._points.length - 1];
  6996. var firstPoint = this._points[0];
  6997. result += (firstPoint.subtract(lastPoint).length());
  6998. }
  6999. return result;
  7000. };
  7001. /**
  7002. * Returns the Path2 internal array of points.
  7003. */
  7004. Path2.prototype.getPoints = function () {
  7005. return this._points;
  7006. };
  7007. /**
  7008. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7009. */
  7010. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7011. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7012. return Vector2.Zero();
  7013. }
  7014. var lengthPosition = normalizedLengthPosition * this.length();
  7015. var previousOffset = 0;
  7016. for (var i = 0; i < this._points.length; i++) {
  7017. var j = (i + 1) % this._points.length;
  7018. var a = this._points[i];
  7019. var b = this._points[j];
  7020. var bToA = b.subtract(a);
  7021. var nextOffset = (bToA.length() + previousOffset);
  7022. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7023. var dir = bToA.normalize();
  7024. var localOffset = lengthPosition - previousOffset;
  7025. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7026. }
  7027. previousOffset = nextOffset;
  7028. }
  7029. return Vector2.Zero();
  7030. };
  7031. /**
  7032. * Returns a new Path2 starting at the coordinates (x, y).
  7033. */
  7034. Path2.StartingAt = function (x, y) {
  7035. return new Path2(x, y);
  7036. };
  7037. return Path2;
  7038. }());
  7039. BABYLON.Path2 = Path2;
  7040. var Path3D = /** @class */ (function () {
  7041. /**
  7042. * new Path3D(path, normal, raw)
  7043. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7044. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7045. * path : an array of Vector3, the curve axis of the Path3D
  7046. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7047. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7048. */
  7049. function Path3D(path, firstNormal, raw) {
  7050. if (firstNormal === void 0) { firstNormal = null; }
  7051. this.path = path;
  7052. this._curve = new Array();
  7053. this._distances = new Array();
  7054. this._tangents = new Array();
  7055. this._normals = new Array();
  7056. this._binormals = new Array();
  7057. for (var p = 0; p < path.length; p++) {
  7058. this._curve[p] = path[p].clone(); // hard copy
  7059. }
  7060. this._raw = raw || false;
  7061. this._compute(firstNormal);
  7062. }
  7063. /**
  7064. * Returns the Path3D array of successive Vector3 designing its curve.
  7065. */
  7066. Path3D.prototype.getCurve = function () {
  7067. return this._curve;
  7068. };
  7069. /**
  7070. * Returns an array populated with tangent vectors on each Path3D curve point.
  7071. */
  7072. Path3D.prototype.getTangents = function () {
  7073. return this._tangents;
  7074. };
  7075. /**
  7076. * Returns an array populated with normal vectors on each Path3D curve point.
  7077. */
  7078. Path3D.prototype.getNormals = function () {
  7079. return this._normals;
  7080. };
  7081. /**
  7082. * Returns an array populated with binormal vectors on each Path3D curve point.
  7083. */
  7084. Path3D.prototype.getBinormals = function () {
  7085. return this._binormals;
  7086. };
  7087. /**
  7088. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7089. */
  7090. Path3D.prototype.getDistances = function () {
  7091. return this._distances;
  7092. };
  7093. /**
  7094. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7095. * Returns the same object updated.
  7096. */
  7097. Path3D.prototype.update = function (path, firstNormal) {
  7098. if (firstNormal === void 0) { firstNormal = null; }
  7099. for (var p = 0; p < path.length; p++) {
  7100. this._curve[p].x = path[p].x;
  7101. this._curve[p].y = path[p].y;
  7102. this._curve[p].z = path[p].z;
  7103. }
  7104. this._compute(firstNormal);
  7105. return this;
  7106. };
  7107. // private function compute() : computes tangents, normals and binormals
  7108. Path3D.prototype._compute = function (firstNormal) {
  7109. var l = this._curve.length;
  7110. // first and last tangents
  7111. this._tangents[0] = this._getFirstNonNullVector(0);
  7112. if (!this._raw) {
  7113. this._tangents[0].normalize();
  7114. }
  7115. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7116. if (!this._raw) {
  7117. this._tangents[l - 1].normalize();
  7118. }
  7119. // normals and binormals at first point : arbitrary vector with _normalVector()
  7120. var tg0 = this._tangents[0];
  7121. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7122. this._normals[0] = pp0;
  7123. if (!this._raw) {
  7124. this._normals[0].normalize();
  7125. }
  7126. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7127. if (!this._raw) {
  7128. this._binormals[0].normalize();
  7129. }
  7130. this._distances[0] = 0.0;
  7131. // normals and binormals : next points
  7132. var prev; // previous vector (segment)
  7133. var cur; // current vector (segment)
  7134. var curTang; // current tangent
  7135. // previous normal
  7136. var prevBinor; // previous binormal
  7137. for (var i = 1; i < l; i++) {
  7138. // tangents
  7139. prev = this._getLastNonNullVector(i);
  7140. if (i < l - 1) {
  7141. cur = this._getFirstNonNullVector(i);
  7142. this._tangents[i] = prev.add(cur);
  7143. this._tangents[i].normalize();
  7144. }
  7145. this._distances[i] = this._distances[i - 1] + prev.length();
  7146. // normals and binormals
  7147. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7148. curTang = this._tangents[i];
  7149. prevBinor = this._binormals[i - 1];
  7150. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7151. if (!this._raw) {
  7152. this._normals[i].normalize();
  7153. }
  7154. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7155. if (!this._raw) {
  7156. this._binormals[i].normalize();
  7157. }
  7158. }
  7159. };
  7160. // private function getFirstNonNullVector(index)
  7161. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7162. Path3D.prototype._getFirstNonNullVector = function (index) {
  7163. var i = 1;
  7164. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7165. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7166. i++;
  7167. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7168. }
  7169. return nNVector;
  7170. };
  7171. // private function getLastNonNullVector(index)
  7172. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7173. Path3D.prototype._getLastNonNullVector = function (index) {
  7174. var i = 1;
  7175. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7176. while (nLVector.length() === 0 && index > i + 1) {
  7177. i++;
  7178. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7179. }
  7180. return nLVector;
  7181. };
  7182. // private function normalVector(v0, vt, va) :
  7183. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7184. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7185. Path3D.prototype._normalVector = function (v0, vt, va) {
  7186. var normal0;
  7187. var tgl = vt.length();
  7188. if (tgl === 0.0) {
  7189. tgl = 1.0;
  7190. }
  7191. if (va === undefined || va === null) {
  7192. var point;
  7193. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7194. point = new Vector3(0.0, -1.0, 0.0);
  7195. }
  7196. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7197. point = new Vector3(1.0, 0.0, 0.0);
  7198. }
  7199. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7200. point = new Vector3(0.0, 0.0, 1.0);
  7201. }
  7202. else {
  7203. point = Vector3.Zero();
  7204. }
  7205. normal0 = Vector3.Cross(vt, point);
  7206. }
  7207. else {
  7208. normal0 = Vector3.Cross(vt, va);
  7209. Vector3.CrossToRef(normal0, vt, normal0);
  7210. }
  7211. normal0.normalize();
  7212. return normal0;
  7213. };
  7214. return Path3D;
  7215. }());
  7216. BABYLON.Path3D = Path3D;
  7217. var Curve3 = /** @class */ (function () {
  7218. /**
  7219. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7220. * A Curve3 is designed from a series of successive Vector3.
  7221. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7222. */
  7223. function Curve3(points) {
  7224. this._length = 0.0;
  7225. this._points = points;
  7226. this._length = this._computeLength(points);
  7227. }
  7228. /**
  7229. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7230. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7231. * @param v1 (Vector3) the control point
  7232. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7233. * @param nbPoints (integer) the wanted number of points in the curve
  7234. */
  7235. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7236. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7237. var bez = new Array();
  7238. var equation = function (t, val0, val1, val2) {
  7239. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7240. return res;
  7241. };
  7242. for (var i = 0; i <= nbPoints; i++) {
  7243. 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)));
  7244. }
  7245. return new Curve3(bez);
  7246. };
  7247. /**
  7248. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7249. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7250. * @param v1 (Vector3) the first control point
  7251. * @param v2 (Vector3) the second control point
  7252. * @param v3 (Vector3) the end point of the Cubic Bezier
  7253. * @param nbPoints (integer) the wanted number of points in the curve
  7254. */
  7255. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7256. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7257. var bez = new Array();
  7258. var equation = function (t, val0, val1, val2, val3) {
  7259. 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;
  7260. return res;
  7261. };
  7262. for (var i = 0; i <= nbPoints; i++) {
  7263. 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)));
  7264. }
  7265. return new Curve3(bez);
  7266. };
  7267. /**
  7268. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7269. * @param p1 (Vector3) the origin point of the Hermite Spline
  7270. * @param t1 (Vector3) the tangent vector at the origin point
  7271. * @param p2 (Vector3) the end point of the Hermite Spline
  7272. * @param t2 (Vector3) the tangent vector at the end point
  7273. * @param nbPoints (integer) the wanted number of points in the curve
  7274. */
  7275. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7276. var hermite = new Array();
  7277. var step = 1.0 / nbPoints;
  7278. for (var i = 0; i <= nbPoints; i++) {
  7279. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7280. }
  7281. return new Curve3(hermite);
  7282. };
  7283. /**
  7284. * Returns a Curve3 object along a CatmullRom Spline curve :
  7285. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7286. * @param nbPoints (integer) the wanted number of points between each curve control points
  7287. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7288. */
  7289. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7290. var catmullRom = new Array();
  7291. var step = 1.0 / nbPoints;
  7292. var amount = 0.0;
  7293. if (closed) {
  7294. var pointsCount = points.length;
  7295. for (var i = 0; i < pointsCount; i++) {
  7296. amount = 0;
  7297. for (var c = 0; c < nbPoints; c++) {
  7298. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7299. amount += step;
  7300. }
  7301. }
  7302. catmullRom.push(catmullRom[0]);
  7303. }
  7304. else {
  7305. var totalPoints = new Array();
  7306. totalPoints.push(points[0].clone());
  7307. Array.prototype.push.apply(totalPoints, points);
  7308. totalPoints.push(points[points.length - 1].clone());
  7309. for (var i = 0; i < totalPoints.length - 3; i++) {
  7310. amount = 0;
  7311. for (var c = 0; c < nbPoints; c++) {
  7312. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7313. amount += step;
  7314. }
  7315. }
  7316. i--;
  7317. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7318. }
  7319. return new Curve3(catmullRom);
  7320. };
  7321. /**
  7322. * Returns the Curve3 stored array of successive Vector3
  7323. */
  7324. Curve3.prototype.getPoints = function () {
  7325. return this._points;
  7326. };
  7327. /**
  7328. * Returns the computed length (float) of the curve.
  7329. */
  7330. Curve3.prototype.length = function () {
  7331. return this._length;
  7332. };
  7333. /**
  7334. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7335. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7336. * curveA and curveB keep unchanged.
  7337. */
  7338. Curve3.prototype.continue = function (curve) {
  7339. var lastPoint = this._points[this._points.length - 1];
  7340. var continuedPoints = this._points.slice();
  7341. var curvePoints = curve.getPoints();
  7342. for (var i = 1; i < curvePoints.length; i++) {
  7343. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7344. }
  7345. var continuedCurve = new Curve3(continuedPoints);
  7346. return continuedCurve;
  7347. };
  7348. Curve3.prototype._computeLength = function (path) {
  7349. var l = 0;
  7350. for (var i = 1; i < path.length; i++) {
  7351. l += (path[i].subtract(path[i - 1])).length();
  7352. }
  7353. return l;
  7354. };
  7355. return Curve3;
  7356. }());
  7357. BABYLON.Curve3 = Curve3;
  7358. // Vertex formats
  7359. var PositionNormalVertex = /** @class */ (function () {
  7360. function PositionNormalVertex(position, normal) {
  7361. if (position === void 0) { position = Vector3.Zero(); }
  7362. if (normal === void 0) { normal = Vector3.Up(); }
  7363. this.position = position;
  7364. this.normal = normal;
  7365. }
  7366. PositionNormalVertex.prototype.clone = function () {
  7367. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7368. };
  7369. return PositionNormalVertex;
  7370. }());
  7371. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7372. var PositionNormalTextureVertex = /** @class */ (function () {
  7373. function PositionNormalTextureVertex(position, normal, uv) {
  7374. if (position === void 0) { position = Vector3.Zero(); }
  7375. if (normal === void 0) { normal = Vector3.Up(); }
  7376. if (uv === void 0) { uv = Vector2.Zero(); }
  7377. this.position = position;
  7378. this.normal = normal;
  7379. this.uv = uv;
  7380. }
  7381. PositionNormalTextureVertex.prototype.clone = function () {
  7382. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7383. };
  7384. return PositionNormalTextureVertex;
  7385. }());
  7386. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7387. // Temporary pre-allocated objects for engine internal use
  7388. // usage in any internal function :
  7389. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7390. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7391. var Tmp = /** @class */ (function () {
  7392. function Tmp() {
  7393. }
  7394. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7395. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7396. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7397. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7398. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7399. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7400. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7401. Matrix.Zero(), Matrix.Zero(),
  7402. Matrix.Zero(), Matrix.Zero(),
  7403. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7404. return Tmp;
  7405. }());
  7406. BABYLON.Tmp = Tmp;
  7407. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7408. var MathTmp = /** @class */ (function () {
  7409. function MathTmp() {
  7410. }
  7411. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7412. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7413. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7414. return MathTmp;
  7415. }());
  7416. })(BABYLON || (BABYLON = {}));
  7417. //# sourceMappingURL=babylon.math.js.map
  7418. var BABYLON;
  7419. (function (BABYLON) {
  7420. var Scalar = /** @class */ (function () {
  7421. function Scalar() {
  7422. }
  7423. /**
  7424. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7425. */
  7426. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7427. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7428. var num = a - b;
  7429. return -epsilon <= num && num <= epsilon;
  7430. };
  7431. /**
  7432. * Returns a string : the upper case translation of the number i to hexadecimal.
  7433. */
  7434. Scalar.ToHex = function (i) {
  7435. var str = i.toString(16);
  7436. if (i <= 15) {
  7437. return ("0" + str).toUpperCase();
  7438. }
  7439. return str.toUpperCase();
  7440. };
  7441. /**
  7442. * Returns -1 if value is negative and +1 is value is positive.
  7443. * Returns the value itself if it's equal to zero.
  7444. */
  7445. Scalar.Sign = function (value) {
  7446. value = +value; // convert to a number
  7447. if (value === 0 || isNaN(value))
  7448. return value;
  7449. return value > 0 ? 1 : -1;
  7450. };
  7451. /**
  7452. * Returns the value itself if it's between min and max.
  7453. * Returns min if the value is lower than min.
  7454. * Returns max if the value is greater than max.
  7455. */
  7456. Scalar.Clamp = function (value, min, max) {
  7457. if (min === void 0) { min = 0; }
  7458. if (max === void 0) { max = 1; }
  7459. return Math.min(max, Math.max(min, value));
  7460. };
  7461. /**
  7462. * Returns the log2 of value.
  7463. */
  7464. Scalar.Log2 = function (value) {
  7465. return Math.log(value) * Math.LOG2E;
  7466. };
  7467. /**
  7468. * Loops the value, so that it is never larger than length and never smaller than 0.
  7469. *
  7470. * This is similar to the modulo operator but it works with floating point numbers.
  7471. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7472. * With t = 5 and length = 2.5, the result would be 0.0.
  7473. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7474. */
  7475. Scalar.Repeat = function (value, length) {
  7476. return value - Math.floor(value / length) * length;
  7477. };
  7478. /**
  7479. * Normalize the value between 0.0 and 1.0 using min and max values
  7480. */
  7481. Scalar.Normalize = function (value, min, max) {
  7482. return (value - min) / (max - min);
  7483. };
  7484. /**
  7485. * Denormalize the value from 0.0 and 1.0 using min and max values
  7486. */
  7487. Scalar.Denormalize = function (normalized, min, max) {
  7488. return (normalized * (max - min) + min);
  7489. };
  7490. /**
  7491. * Calculates the shortest difference between two given angles given in degrees.
  7492. */
  7493. Scalar.DeltaAngle = function (current, target) {
  7494. var num = Scalar.Repeat(target - current, 360.0);
  7495. if (num > 180.0) {
  7496. num -= 360.0;
  7497. }
  7498. return num;
  7499. };
  7500. /**
  7501. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7502. *
  7503. * The returned value will move back and forth between 0 and length
  7504. */
  7505. Scalar.PingPong = function (tx, length) {
  7506. var t = Scalar.Repeat(tx, length * 2.0);
  7507. return length - Math.abs(t - length);
  7508. };
  7509. /**
  7510. * Interpolates between min and max with smoothing at the limits.
  7511. *
  7512. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7513. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7514. */
  7515. Scalar.SmoothStep = function (from, to, tx) {
  7516. var t = Scalar.Clamp(tx);
  7517. t = -2.0 * t * t * t + 3.0 * t * t;
  7518. return to * t + from * (1.0 - t);
  7519. };
  7520. /**
  7521. * Moves a value current towards target.
  7522. *
  7523. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7524. * Negative values of maxDelta pushes the value away from target.
  7525. */
  7526. Scalar.MoveTowards = function (current, target, maxDelta) {
  7527. var result = 0;
  7528. if (Math.abs(target - current) <= maxDelta) {
  7529. result = target;
  7530. }
  7531. else {
  7532. result = current + Scalar.Sign(target - current) * maxDelta;
  7533. }
  7534. return result;
  7535. };
  7536. /**
  7537. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7538. *
  7539. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7540. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7541. */
  7542. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7543. var num = Scalar.DeltaAngle(current, target);
  7544. var result = 0;
  7545. if (-maxDelta < num && num < maxDelta) {
  7546. result = target;
  7547. }
  7548. else {
  7549. target = current + num;
  7550. result = Scalar.MoveTowards(current, target, maxDelta);
  7551. }
  7552. return result;
  7553. };
  7554. /**
  7555. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7556. */
  7557. Scalar.Lerp = function (start, end, amount) {
  7558. return start + ((end - start) * amount);
  7559. };
  7560. /**
  7561. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7562. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7563. */
  7564. Scalar.LerpAngle = function (start, end, amount) {
  7565. var num = Scalar.Repeat(end - start, 360.0);
  7566. if (num > 180.0) {
  7567. num -= 360.0;
  7568. }
  7569. return start + num * Scalar.Clamp(amount);
  7570. };
  7571. /**
  7572. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7573. */
  7574. Scalar.InverseLerp = function (a, b, value) {
  7575. var result = 0;
  7576. if (a != b) {
  7577. result = Scalar.Clamp((value - a) / (b - a));
  7578. }
  7579. else {
  7580. result = 0.0;
  7581. }
  7582. return result;
  7583. };
  7584. /**
  7585. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7586. */
  7587. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7588. var squared = amount * amount;
  7589. var cubed = amount * squared;
  7590. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7591. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7592. var part3 = (cubed - (2.0 * squared)) + amount;
  7593. var part4 = cubed - squared;
  7594. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7595. };
  7596. /**
  7597. * Returns a random float number between and min and max values
  7598. */
  7599. Scalar.RandomRange = function (min, max) {
  7600. if (min === max)
  7601. return min;
  7602. return ((Math.random() * (max - min)) + min);
  7603. };
  7604. /**
  7605. * This function returns percentage of a number in a given range.
  7606. *
  7607. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7608. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7609. */
  7610. Scalar.RangeToPercent = function (number, min, max) {
  7611. return ((number - min) / (max - min));
  7612. };
  7613. /**
  7614. * This function returns number that corresponds to the percentage in a given range.
  7615. *
  7616. * PercentToRange(0.34,0,100) will return 34.
  7617. */
  7618. Scalar.PercentToRange = function (percent, min, max) {
  7619. return ((max - min) * percent + min);
  7620. };
  7621. /**
  7622. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7623. * @param angle The angle to normalize in radian.
  7624. * @return The converted angle.
  7625. */
  7626. Scalar.NormalizeRadians = function (angle) {
  7627. // More precise but slower version kept for reference.
  7628. // angle = angle % Tools.TwoPi;
  7629. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7630. //if (angle > Math.PI) {
  7631. // angle -= Tools.TwoPi;
  7632. //}
  7633. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7634. return angle;
  7635. };
  7636. /**
  7637. * Two pi constants convenient for computation.
  7638. */
  7639. Scalar.TwoPi = Math.PI * 2;
  7640. return Scalar;
  7641. }());
  7642. BABYLON.Scalar = Scalar;
  7643. })(BABYLON || (BABYLON = {}));
  7644. //# sourceMappingURL=babylon.math.scalar.js.map
  7645. //# sourceMappingURL=babylon.mixins.js.map
  7646. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7647. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7648. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7649. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7650. //# sourceMappingURL=babylon.webgl2.js.map
  7651. var BABYLON;
  7652. (function (BABYLON) {
  7653. var __decoratorInitialStore = {};
  7654. var __mergedStore = {};
  7655. var _copySource = function (creationFunction, source, instanciate) {
  7656. var destination = creationFunction();
  7657. // Tags
  7658. if (BABYLON.Tags) {
  7659. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7660. }
  7661. var classStore = getMergedStore(destination);
  7662. // Properties
  7663. for (var property in classStore) {
  7664. var propertyDescriptor = classStore[property];
  7665. var sourceProperty = source[property];
  7666. var propertyType = propertyDescriptor.type;
  7667. if (sourceProperty !== undefined && sourceProperty !== null) {
  7668. switch (propertyType) {
  7669. case 0: // Value
  7670. case 6: // Mesh reference
  7671. case 11: // Camera reference
  7672. destination[property] = sourceProperty;
  7673. break;
  7674. case 1: // Texture
  7675. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7676. break;
  7677. case 2: // Color3
  7678. case 3: // FresnelParameters
  7679. case 4: // Vector2
  7680. case 5: // Vector3
  7681. case 7: // Color Curves
  7682. case 10: // Quaternion
  7683. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7684. break;
  7685. }
  7686. }
  7687. }
  7688. return destination;
  7689. };
  7690. function getDirectStore(target) {
  7691. var classKey = target.getClassName();
  7692. if (!__decoratorInitialStore[classKey]) {
  7693. __decoratorInitialStore[classKey] = {};
  7694. }
  7695. return __decoratorInitialStore[classKey];
  7696. }
  7697. /**
  7698. * Return the list of properties flagged as serializable
  7699. * @param target: host object
  7700. */
  7701. function getMergedStore(target) {
  7702. var classKey = target.getClassName();
  7703. if (__mergedStore[classKey]) {
  7704. return __mergedStore[classKey];
  7705. }
  7706. __mergedStore[classKey] = {};
  7707. var store = __mergedStore[classKey];
  7708. var currentTarget = target;
  7709. var currentKey = classKey;
  7710. while (currentKey) {
  7711. var initialStore = __decoratorInitialStore[currentKey];
  7712. for (var property in initialStore) {
  7713. store[property] = initialStore[property];
  7714. }
  7715. var parent_1 = void 0;
  7716. var done = false;
  7717. do {
  7718. parent_1 = Object.getPrototypeOf(currentTarget);
  7719. if (!parent_1.getClassName) {
  7720. done = true;
  7721. break;
  7722. }
  7723. if (parent_1.getClassName() !== currentKey) {
  7724. break;
  7725. }
  7726. currentTarget = parent_1;
  7727. } while (parent_1);
  7728. if (done) {
  7729. break;
  7730. }
  7731. currentKey = parent_1.getClassName();
  7732. currentTarget = parent_1;
  7733. }
  7734. return store;
  7735. }
  7736. function generateSerializableMember(type, sourceName) {
  7737. return function (target, propertyKey) {
  7738. var classStore = getDirectStore(target);
  7739. if (!classStore[propertyKey]) {
  7740. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7741. }
  7742. };
  7743. }
  7744. function generateExpandMember(setCallback, targetKey) {
  7745. if (targetKey === void 0) { targetKey = null; }
  7746. return function (target, propertyKey) {
  7747. var key = targetKey || ("_" + propertyKey);
  7748. Object.defineProperty(target, propertyKey, {
  7749. get: function () {
  7750. return this[key];
  7751. },
  7752. set: function (value) {
  7753. if (this[key] === value) {
  7754. return;
  7755. }
  7756. this[key] = value;
  7757. target[setCallback].apply(this);
  7758. },
  7759. enumerable: true,
  7760. configurable: true
  7761. });
  7762. };
  7763. }
  7764. function expandToProperty(callback, targetKey) {
  7765. if (targetKey === void 0) { targetKey = null; }
  7766. return generateExpandMember(callback, targetKey);
  7767. }
  7768. BABYLON.expandToProperty = expandToProperty;
  7769. function serialize(sourceName) {
  7770. return generateSerializableMember(0, sourceName); // value member
  7771. }
  7772. BABYLON.serialize = serialize;
  7773. function serializeAsTexture(sourceName) {
  7774. return generateSerializableMember(1, sourceName); // texture member
  7775. }
  7776. BABYLON.serializeAsTexture = serializeAsTexture;
  7777. function serializeAsColor3(sourceName) {
  7778. return generateSerializableMember(2, sourceName); // color3 member
  7779. }
  7780. BABYLON.serializeAsColor3 = serializeAsColor3;
  7781. function serializeAsFresnelParameters(sourceName) {
  7782. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7783. }
  7784. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7785. function serializeAsVector2(sourceName) {
  7786. return generateSerializableMember(4, sourceName); // vector2 member
  7787. }
  7788. BABYLON.serializeAsVector2 = serializeAsVector2;
  7789. function serializeAsVector3(sourceName) {
  7790. return generateSerializableMember(5, sourceName); // vector3 member
  7791. }
  7792. BABYLON.serializeAsVector3 = serializeAsVector3;
  7793. function serializeAsMeshReference(sourceName) {
  7794. return generateSerializableMember(6, sourceName); // mesh reference member
  7795. }
  7796. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7797. function serializeAsColorCurves(sourceName) {
  7798. return generateSerializableMember(7, sourceName); // color curves
  7799. }
  7800. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7801. function serializeAsColor4(sourceName) {
  7802. return generateSerializableMember(8, sourceName); // color 4
  7803. }
  7804. BABYLON.serializeAsColor4 = serializeAsColor4;
  7805. function serializeAsImageProcessingConfiguration(sourceName) {
  7806. return generateSerializableMember(9, sourceName); // image processing
  7807. }
  7808. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7809. function serializeAsQuaternion(sourceName) {
  7810. return generateSerializableMember(10, sourceName); // quaternion member
  7811. }
  7812. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7813. /**
  7814. * Decorator used to define property that can be serialized as reference to a camera
  7815. * @param sourceName defines the name of the property to decorate
  7816. */
  7817. function serializeAsCameraReference(sourceName) {
  7818. return generateSerializableMember(11, sourceName); // camera reference member
  7819. }
  7820. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7821. var SerializationHelper = /** @class */ (function () {
  7822. function SerializationHelper() {
  7823. }
  7824. SerializationHelper.Serialize = function (entity, serializationObject) {
  7825. if (!serializationObject) {
  7826. serializationObject = {};
  7827. }
  7828. // Tags
  7829. if (BABYLON.Tags) {
  7830. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7831. }
  7832. var serializedProperties = getMergedStore(entity);
  7833. // Properties
  7834. for (var property in serializedProperties) {
  7835. var propertyDescriptor = serializedProperties[property];
  7836. var targetPropertyName = propertyDescriptor.sourceName || property;
  7837. var propertyType = propertyDescriptor.type;
  7838. var sourceProperty = entity[property];
  7839. if (sourceProperty !== undefined && sourceProperty !== null) {
  7840. switch (propertyType) {
  7841. case 0: // Value
  7842. serializationObject[targetPropertyName] = sourceProperty;
  7843. break;
  7844. case 1: // Texture
  7845. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7846. break;
  7847. case 2: // Color3
  7848. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7849. break;
  7850. case 3: // FresnelParameters
  7851. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7852. break;
  7853. case 4: // Vector2
  7854. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7855. break;
  7856. case 5: // Vector3
  7857. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7858. break;
  7859. case 6: // Mesh reference
  7860. serializationObject[targetPropertyName] = sourceProperty.id;
  7861. break;
  7862. case 7: // Color Curves
  7863. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7864. break;
  7865. case 8: // Color 4
  7866. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7867. break;
  7868. case 9: // Image Processing
  7869. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7870. break;
  7871. case 10: // Quaternion
  7872. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7873. break;
  7874. case 11: // Camera reference
  7875. serializationObject[targetPropertyName] = sourceProperty.id;
  7876. break;
  7877. }
  7878. }
  7879. }
  7880. return serializationObject;
  7881. };
  7882. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7883. if (rootUrl === void 0) { rootUrl = null; }
  7884. var destination = creationFunction();
  7885. if (!rootUrl) {
  7886. rootUrl = "";
  7887. }
  7888. // Tags
  7889. if (BABYLON.Tags) {
  7890. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7891. }
  7892. var classStore = getMergedStore(destination);
  7893. // Properties
  7894. for (var property in classStore) {
  7895. var propertyDescriptor = classStore[property];
  7896. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7897. var propertyType = propertyDescriptor.type;
  7898. if (sourceProperty !== undefined && sourceProperty !== null) {
  7899. var dest = destination;
  7900. switch (propertyType) {
  7901. case 0: // Value
  7902. dest[property] = sourceProperty;
  7903. break;
  7904. case 1: // Texture
  7905. if (scene) {
  7906. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7907. }
  7908. break;
  7909. case 2: // Color3
  7910. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7911. break;
  7912. case 3: // FresnelParameters
  7913. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7914. break;
  7915. case 4: // Vector2
  7916. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7917. break;
  7918. case 5: // Vector3
  7919. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7920. break;
  7921. case 6: // Mesh reference
  7922. if (scene) {
  7923. dest[property] = scene.getLastMeshByID(sourceProperty);
  7924. }
  7925. break;
  7926. case 7: // Color Curves
  7927. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7928. break;
  7929. case 8: // Color 4
  7930. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7931. break;
  7932. case 9: // Image Processing
  7933. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7934. break;
  7935. case 10: // Quaternion
  7936. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7937. break;
  7938. case 11: // Camera reference
  7939. if (scene) {
  7940. dest[property] = scene.getCameraByID(sourceProperty);
  7941. }
  7942. break;
  7943. }
  7944. }
  7945. }
  7946. return destination;
  7947. };
  7948. SerializationHelper.Clone = function (creationFunction, source) {
  7949. return _copySource(creationFunction, source, false);
  7950. };
  7951. SerializationHelper.Instanciate = function (creationFunction, source) {
  7952. return _copySource(creationFunction, source, true);
  7953. };
  7954. return SerializationHelper;
  7955. }());
  7956. BABYLON.SerializationHelper = SerializationHelper;
  7957. })(BABYLON || (BABYLON = {}));
  7958. //# sourceMappingURL=babylon.decorators.js.map
  7959. var BABYLON;
  7960. (function (BABYLON) {
  7961. /**
  7962. * Wrapper class for promise with external resolve and reject.
  7963. */
  7964. var Deferred = /** @class */ (function () {
  7965. /**
  7966. * Constructor for this deferred object.
  7967. */
  7968. function Deferred() {
  7969. var _this = this;
  7970. this.promise = new Promise(function (resolve, reject) {
  7971. _this._resolve = resolve;
  7972. _this._reject = reject;
  7973. });
  7974. }
  7975. Object.defineProperty(Deferred.prototype, "resolve", {
  7976. /**
  7977. * The resolve method of the promise associated with this deferred object.
  7978. */
  7979. get: function () {
  7980. return this._resolve;
  7981. },
  7982. enumerable: true,
  7983. configurable: true
  7984. });
  7985. Object.defineProperty(Deferred.prototype, "reject", {
  7986. /**
  7987. * The reject method of the promise associated with this deferred object.
  7988. */
  7989. get: function () {
  7990. return this._reject;
  7991. },
  7992. enumerable: true,
  7993. configurable: true
  7994. });
  7995. return Deferred;
  7996. }());
  7997. BABYLON.Deferred = Deferred;
  7998. })(BABYLON || (BABYLON = {}));
  7999. //# sourceMappingURL=babylon.deferred.js.map
  8000. var BABYLON;
  8001. (function (BABYLON) {
  8002. /**
  8003. * A class serves as a medium between the observable and its observers
  8004. */
  8005. var EventState = /** @class */ (function () {
  8006. /**
  8007. * Create a new EventState
  8008. * @param mask defines the mask associated with this state
  8009. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8010. * @param target defines the original target of the state
  8011. * @param currentTarget defines the current target of the state
  8012. */
  8013. function EventState(mask, skipNextObservers, target, currentTarget) {
  8014. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8015. this.initalize(mask, skipNextObservers, target, currentTarget);
  8016. }
  8017. /**
  8018. * Initialize the current event state
  8019. * @param mask defines the mask associated with this state
  8020. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8021. * @param target defines the original target of the state
  8022. * @param currentTarget defines the current target of the state
  8023. * @returns the current event state
  8024. */
  8025. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8026. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8027. this.mask = mask;
  8028. this.skipNextObservers = skipNextObservers;
  8029. this.target = target;
  8030. this.currentTarget = currentTarget;
  8031. return this;
  8032. };
  8033. return EventState;
  8034. }());
  8035. BABYLON.EventState = EventState;
  8036. /**
  8037. * Represent an Observer registered to a given Observable object.
  8038. */
  8039. var Observer = /** @class */ (function () {
  8040. /**
  8041. * Creates a new observer
  8042. * @param callback defines the callback to call when the observer is notified
  8043. * @param mask defines the mask of the observer (used to filter notifications)
  8044. * @param scope defines the current scope used to restore the JS context
  8045. */
  8046. function Observer(
  8047. /**
  8048. * Defines the callback to call when the observer is notified
  8049. */
  8050. callback,
  8051. /**
  8052. * Defines the mask of the observer (used to filter notifications)
  8053. */
  8054. mask,
  8055. /**
  8056. * Defines the current scope used to restore the JS context
  8057. */
  8058. scope) {
  8059. if (scope === void 0) { scope = null; }
  8060. this.callback = callback;
  8061. this.mask = mask;
  8062. this.scope = scope;
  8063. /** @hidden */
  8064. this._willBeUnregistered = false;
  8065. /**
  8066. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8067. */
  8068. this.unregisterOnNextCall = false;
  8069. }
  8070. return Observer;
  8071. }());
  8072. BABYLON.Observer = Observer;
  8073. /**
  8074. * Represent a list of observers registered to multiple Observables object.
  8075. */
  8076. var MultiObserver = /** @class */ (function () {
  8077. function MultiObserver() {
  8078. }
  8079. /**
  8080. * Release associated resources
  8081. */
  8082. MultiObserver.prototype.dispose = function () {
  8083. if (this._observers && this._observables) {
  8084. for (var index = 0; index < this._observers.length; index++) {
  8085. this._observables[index].remove(this._observers[index]);
  8086. }
  8087. }
  8088. this._observers = null;
  8089. this._observables = null;
  8090. };
  8091. /**
  8092. * Raise a callback when one of the observable will notify
  8093. * @param observables defines a list of observables to watch
  8094. * @param callback defines the callback to call on notification
  8095. * @param mask defines the mask used to filter notifications
  8096. * @param scope defines the current scope used to restore the JS context
  8097. * @returns the new MultiObserver
  8098. */
  8099. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8100. if (mask === void 0) { mask = -1; }
  8101. if (scope === void 0) { scope = null; }
  8102. var result = new MultiObserver();
  8103. result._observers = new Array();
  8104. result._observables = observables;
  8105. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8106. var observable = observables_1[_i];
  8107. var observer = observable.add(callback, mask, false, scope);
  8108. if (observer) {
  8109. result._observers.push(observer);
  8110. }
  8111. }
  8112. return result;
  8113. };
  8114. return MultiObserver;
  8115. }());
  8116. BABYLON.MultiObserver = MultiObserver;
  8117. /**
  8118. * The Observable class is a simple implementation of the Observable pattern.
  8119. *
  8120. * 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.
  8121. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8122. * 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).
  8123. * 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.
  8124. */
  8125. var Observable = /** @class */ (function () {
  8126. /**
  8127. * Creates a new observable
  8128. * @param onObserverAdded defines a callback to call when a new observer is added
  8129. */
  8130. function Observable(onObserverAdded) {
  8131. this._observers = new Array();
  8132. this._eventState = new EventState(0);
  8133. if (onObserverAdded) {
  8134. this._onObserverAdded = onObserverAdded;
  8135. }
  8136. }
  8137. /**
  8138. * Create a new Observer with the specified callback
  8139. * @param callback the callback that will be executed for that Observer
  8140. * @param mask the mask used to filter observers
  8141. * @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.
  8142. * @param scope optional scope for the callback to be called from
  8143. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8144. * @returns the new observer created for the callback
  8145. */
  8146. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8147. if (mask === void 0) { mask = -1; }
  8148. if (insertFirst === void 0) { insertFirst = false; }
  8149. if (scope === void 0) { scope = null; }
  8150. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8151. if (!callback) {
  8152. return null;
  8153. }
  8154. var observer = new Observer(callback, mask, scope);
  8155. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8156. if (insertFirst) {
  8157. this._observers.unshift(observer);
  8158. }
  8159. else {
  8160. this._observers.push(observer);
  8161. }
  8162. if (this._onObserverAdded) {
  8163. this._onObserverAdded(observer);
  8164. }
  8165. return observer;
  8166. };
  8167. /**
  8168. * Create a new Observer with the specified callback and unregisters after the next notification
  8169. * @param callback the callback that will be executed for that Observer
  8170. * @returns the new observer created for the callback
  8171. */
  8172. Observable.prototype.addOnce = function (callback) {
  8173. return this.add(callback, undefined, undefined, undefined, true);
  8174. };
  8175. /**
  8176. * Remove an Observer from the Observable object
  8177. * @param observer the instance of the Observer to remove
  8178. * @returns false if it doesn't belong to this Observable
  8179. */
  8180. Observable.prototype.remove = function (observer) {
  8181. if (!observer) {
  8182. return false;
  8183. }
  8184. var index = this._observers.indexOf(observer);
  8185. if (index !== -1) {
  8186. this._observers.splice(index, 1);
  8187. return true;
  8188. }
  8189. return false;
  8190. };
  8191. /**
  8192. * Remove a callback from the Observable object
  8193. * @param callback the callback to remove
  8194. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8195. * @returns false if it doesn't belong to this Observable
  8196. */
  8197. Observable.prototype.removeCallback = function (callback, scope) {
  8198. for (var index = 0; index < this._observers.length; index++) {
  8199. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8200. this._observers.splice(index, 1);
  8201. return true;
  8202. }
  8203. }
  8204. return false;
  8205. };
  8206. Observable.prototype._deferUnregister = function (observer) {
  8207. var _this = this;
  8208. observer.unregisterOnNextCall = false;
  8209. observer._willBeUnregistered = true;
  8210. BABYLON.Tools.SetImmediate(function () {
  8211. _this.remove(observer);
  8212. });
  8213. };
  8214. /**
  8215. * Notify all Observers by calling their respective callback with the given data
  8216. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8217. * @param eventData defines the data to send to all observers
  8218. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8219. * @param target defines the original target of the state
  8220. * @param currentTarget defines the current target of the state
  8221. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8222. */
  8223. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8224. if (mask === void 0) { mask = -1; }
  8225. if (!this._observers.length) {
  8226. return true;
  8227. }
  8228. var state = this._eventState;
  8229. state.mask = mask;
  8230. state.target = target;
  8231. state.currentTarget = currentTarget;
  8232. state.skipNextObservers = false;
  8233. state.lastReturnValue = eventData;
  8234. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8235. var obs = _a[_i];
  8236. if (obs._willBeUnregistered) {
  8237. continue;
  8238. }
  8239. if (obs.mask & mask) {
  8240. if (obs.scope) {
  8241. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8242. }
  8243. else {
  8244. state.lastReturnValue = obs.callback(eventData, state);
  8245. }
  8246. if (obs.unregisterOnNextCall) {
  8247. this._deferUnregister(obs);
  8248. }
  8249. }
  8250. if (state.skipNextObservers) {
  8251. return false;
  8252. }
  8253. }
  8254. return true;
  8255. };
  8256. /**
  8257. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8258. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8259. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8260. * and it is crucial that all callbacks will be executed.
  8261. * The order of the callbacks is kept, callbacks are not executed parallel.
  8262. *
  8263. * @param eventData The data to be sent to each callback
  8264. * @param mask is used to filter observers defaults to -1
  8265. * @param target defines the callback target (see EventState)
  8266. * @param currentTarget defines he current object in the bubbling phase
  8267. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8268. */
  8269. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8270. var _this = this;
  8271. if (mask === void 0) { mask = -1; }
  8272. // create an empty promise
  8273. var p = Promise.resolve(eventData);
  8274. // no observers? return this promise.
  8275. if (!this._observers.length) {
  8276. return p;
  8277. }
  8278. var state = this._eventState;
  8279. state.mask = mask;
  8280. state.target = target;
  8281. state.currentTarget = currentTarget;
  8282. state.skipNextObservers = false;
  8283. // execute one callback after another (not using Promise.all, the order is important)
  8284. this._observers.forEach(function (obs) {
  8285. if (state.skipNextObservers) {
  8286. return;
  8287. }
  8288. if (obs._willBeUnregistered) {
  8289. return;
  8290. }
  8291. if (obs.mask & mask) {
  8292. if (obs.scope) {
  8293. p = p.then(function (lastReturnedValue) {
  8294. state.lastReturnValue = lastReturnedValue;
  8295. return obs.callback.apply(obs.scope, [eventData, state]);
  8296. });
  8297. }
  8298. else {
  8299. p = p.then(function (lastReturnedValue) {
  8300. state.lastReturnValue = lastReturnedValue;
  8301. return obs.callback(eventData, state);
  8302. });
  8303. }
  8304. if (obs.unregisterOnNextCall) {
  8305. _this._deferUnregister(obs);
  8306. }
  8307. }
  8308. });
  8309. // return the eventData
  8310. return p.then(function () { return eventData; });
  8311. };
  8312. /**
  8313. * Notify a specific observer
  8314. * @param observer defines the observer to notify
  8315. * @param eventData defines the data to be sent to each callback
  8316. * @param mask is used to filter observers defaults to -1
  8317. */
  8318. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8319. if (mask === void 0) { mask = -1; }
  8320. var state = this._eventState;
  8321. state.mask = mask;
  8322. state.skipNextObservers = false;
  8323. observer.callback(eventData, state);
  8324. };
  8325. /**
  8326. * Gets a boolean indicating if the observable has at least one observer
  8327. * @returns true is the Observable has at least one Observer registered
  8328. */
  8329. Observable.prototype.hasObservers = function () {
  8330. return this._observers.length > 0;
  8331. };
  8332. /**
  8333. * Clear the list of observers
  8334. */
  8335. Observable.prototype.clear = function () {
  8336. this._observers = new Array();
  8337. this._onObserverAdded = null;
  8338. };
  8339. /**
  8340. * Clone the current observable
  8341. * @returns a new observable
  8342. */
  8343. Observable.prototype.clone = function () {
  8344. var result = new Observable();
  8345. result._observers = this._observers.slice(0);
  8346. return result;
  8347. };
  8348. /**
  8349. * Does this observable handles observer registered with a given mask
  8350. * @param mask defines the mask to be tested
  8351. * @return whether or not one observer registered with the given mask is handeled
  8352. **/
  8353. Observable.prototype.hasSpecificMask = function (mask) {
  8354. if (mask === void 0) { mask = -1; }
  8355. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8356. var obs = _a[_i];
  8357. if (obs.mask & mask || obs.mask === mask) {
  8358. return true;
  8359. }
  8360. }
  8361. return false;
  8362. };
  8363. return Observable;
  8364. }());
  8365. BABYLON.Observable = Observable;
  8366. })(BABYLON || (BABYLON = {}));
  8367. //# sourceMappingURL=babylon.observable.js.map
  8368. var BABYLON;
  8369. (function (BABYLON) {
  8370. var SmartArray = /** @class */ (function () {
  8371. function SmartArray(capacity) {
  8372. this.length = 0;
  8373. this.data = new Array(capacity);
  8374. this._id = SmartArray._GlobalId++;
  8375. }
  8376. SmartArray.prototype.push = function (value) {
  8377. this.data[this.length++] = value;
  8378. if (this.length > this.data.length) {
  8379. this.data.length *= 2;
  8380. }
  8381. };
  8382. SmartArray.prototype.forEach = function (func) {
  8383. for (var index = 0; index < this.length; index++) {
  8384. func(this.data[index]);
  8385. }
  8386. };
  8387. SmartArray.prototype.sort = function (compareFn) {
  8388. this.data.sort(compareFn);
  8389. };
  8390. SmartArray.prototype.reset = function () {
  8391. this.length = 0;
  8392. };
  8393. SmartArray.prototype.dispose = function () {
  8394. this.reset();
  8395. if (this.data) {
  8396. this.data.length = 0;
  8397. this.data = [];
  8398. }
  8399. };
  8400. SmartArray.prototype.concat = function (array) {
  8401. if (array.length === 0) {
  8402. return;
  8403. }
  8404. if (this.length + array.length > this.data.length) {
  8405. this.data.length = (this.length + array.length) * 2;
  8406. }
  8407. for (var index = 0; index < array.length; index++) {
  8408. this.data[this.length++] = (array.data || array)[index];
  8409. }
  8410. };
  8411. SmartArray.prototype.indexOf = function (value) {
  8412. var position = this.data.indexOf(value);
  8413. if (position >= this.length) {
  8414. return -1;
  8415. }
  8416. return position;
  8417. };
  8418. SmartArray.prototype.contains = function (value) {
  8419. return this.data.indexOf(value) !== -1;
  8420. };
  8421. // Statics
  8422. SmartArray._GlobalId = 0;
  8423. return SmartArray;
  8424. }());
  8425. BABYLON.SmartArray = SmartArray;
  8426. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8427. __extends(SmartArrayNoDuplicate, _super);
  8428. function SmartArrayNoDuplicate() {
  8429. var _this = _super !== null && _super.apply(this, arguments) || this;
  8430. _this._duplicateId = 0;
  8431. return _this;
  8432. }
  8433. SmartArrayNoDuplicate.prototype.push = function (value) {
  8434. _super.prototype.push.call(this, value);
  8435. if (!value.__smartArrayFlags) {
  8436. value.__smartArrayFlags = {};
  8437. }
  8438. value.__smartArrayFlags[this._id] = this._duplicateId;
  8439. };
  8440. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8441. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8442. return false;
  8443. }
  8444. this.push(value);
  8445. return true;
  8446. };
  8447. SmartArrayNoDuplicate.prototype.reset = function () {
  8448. _super.prototype.reset.call(this);
  8449. this._duplicateId++;
  8450. };
  8451. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8452. if (array.length === 0) {
  8453. return;
  8454. }
  8455. if (this.length + array.length > this.data.length) {
  8456. this.data.length = (this.length + array.length) * 2;
  8457. }
  8458. for (var index = 0; index < array.length; index++) {
  8459. var item = (array.data || array)[index];
  8460. this.pushNoDuplicate(item);
  8461. }
  8462. };
  8463. return SmartArrayNoDuplicate;
  8464. }(SmartArray));
  8465. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8466. })(BABYLON || (BABYLON = {}));
  8467. //# sourceMappingURL=babylon.smartArray.js.map
  8468. var BABYLON;
  8469. (function (BABYLON) {
  8470. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8471. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8472. var LoadFileError = /** @class */ (function (_super) {
  8473. __extends(LoadFileError, _super);
  8474. function LoadFileError(message, request) {
  8475. var _this = _super.call(this, message) || this;
  8476. _this.request = request;
  8477. _this.name = "LoadFileError";
  8478. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8479. return _this;
  8480. }
  8481. // Polyfill for Object.setPrototypeOf if necessary.
  8482. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8483. return LoadFileError;
  8484. }(Error));
  8485. BABYLON.LoadFileError = LoadFileError;
  8486. var RetryStrategy = /** @class */ (function () {
  8487. function RetryStrategy() {
  8488. }
  8489. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8490. if (maxRetries === void 0) { maxRetries = 3; }
  8491. if (baseInterval === void 0) { baseInterval = 500; }
  8492. return function (url, request, retryIndex) {
  8493. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8494. return -1;
  8495. }
  8496. return Math.pow(2, retryIndex) * baseInterval;
  8497. };
  8498. };
  8499. return RetryStrategy;
  8500. }());
  8501. BABYLON.RetryStrategy = RetryStrategy;
  8502. // Screenshots
  8503. var screenshotCanvas;
  8504. var cloneValue = function (source, destinationObject) {
  8505. if (!source)
  8506. return null;
  8507. if (source instanceof BABYLON.Mesh) {
  8508. return null;
  8509. }
  8510. if (source instanceof BABYLON.SubMesh) {
  8511. return source.clone(destinationObject);
  8512. }
  8513. else if (source.clone) {
  8514. return source.clone();
  8515. }
  8516. return null;
  8517. };
  8518. var Tools = /** @class */ (function () {
  8519. function Tools() {
  8520. }
  8521. /**
  8522. * Interpolates between a and b via alpha
  8523. * @param a The lower value (returned when alpha = 0)
  8524. * @param b The upper value (returned when alpha = 1)
  8525. * @param alpha The interpolation-factor
  8526. * @return The mixed value
  8527. */
  8528. Tools.Mix = function (a, b, alpha) {
  8529. return a * (1 - alpha) + b * alpha;
  8530. };
  8531. Tools.Instantiate = function (className) {
  8532. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8533. return Tools.RegisteredExternalClasses[className];
  8534. }
  8535. var arr = className.split(".");
  8536. var fn = (window || this);
  8537. for (var i = 0, len = arr.length; i < len; i++) {
  8538. fn = fn[arr[i]];
  8539. }
  8540. if (typeof fn !== "function") {
  8541. return null;
  8542. }
  8543. return fn;
  8544. };
  8545. /**
  8546. * Provides a slice function that will work even on IE
  8547. * @param data defines the array to slice
  8548. * @param start defines the start of the data (optional)
  8549. * @param end defines the end of the data (optional)
  8550. * @returns the new sliced array
  8551. */
  8552. Tools.Slice = function (data, start, end) {
  8553. if (data.slice) {
  8554. return data.slice(start, end);
  8555. }
  8556. return Array.prototype.slice.call(data, start, end);
  8557. };
  8558. Tools.SetImmediate = function (action) {
  8559. if (window.setImmediate) {
  8560. window.setImmediate(action);
  8561. }
  8562. else {
  8563. setTimeout(action, 1);
  8564. }
  8565. };
  8566. Tools.IsExponentOfTwo = function (value) {
  8567. var count = 1;
  8568. do {
  8569. count *= 2;
  8570. } while (count < value);
  8571. return count === value;
  8572. };
  8573. /**
  8574. * Returns the nearest 32-bit single precision float representation of a Number
  8575. * @param value A Number. If the parameter is of a different type, it will get converted
  8576. * to a number or to NaN if it cannot be converted
  8577. * @returns number
  8578. */
  8579. Tools.FloatRound = function (value) {
  8580. if (Math.fround) {
  8581. return Math.fround(value);
  8582. }
  8583. return (Tools._tmpFloatArray[0] = value);
  8584. };
  8585. /**
  8586. * Find the next highest power of two.
  8587. * @param x Number to start search from.
  8588. * @return Next highest power of two.
  8589. */
  8590. Tools.CeilingPOT = function (x) {
  8591. x--;
  8592. x |= x >> 1;
  8593. x |= x >> 2;
  8594. x |= x >> 4;
  8595. x |= x >> 8;
  8596. x |= x >> 16;
  8597. x++;
  8598. return x;
  8599. };
  8600. /**
  8601. * Find the next lowest power of two.
  8602. * @param x Number to start search from.
  8603. * @return Next lowest power of two.
  8604. */
  8605. Tools.FloorPOT = function (x) {
  8606. x = x | (x >> 1);
  8607. x = x | (x >> 2);
  8608. x = x | (x >> 4);
  8609. x = x | (x >> 8);
  8610. x = x | (x >> 16);
  8611. return x - (x >> 1);
  8612. };
  8613. /**
  8614. * Find the nearest power of two.
  8615. * @param x Number to start search from.
  8616. * @return Next nearest power of two.
  8617. */
  8618. Tools.NearestPOT = function (x) {
  8619. var c = Tools.CeilingPOT(x);
  8620. var f = Tools.FloorPOT(x);
  8621. return (c - x) > (x - f) ? f : c;
  8622. };
  8623. Tools.GetExponentOfTwo = function (value, max, mode) {
  8624. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8625. var pot;
  8626. switch (mode) {
  8627. case BABYLON.Engine.SCALEMODE_FLOOR:
  8628. pot = Tools.FloorPOT(value);
  8629. break;
  8630. case BABYLON.Engine.SCALEMODE_NEAREST:
  8631. pot = Tools.NearestPOT(value);
  8632. break;
  8633. case BABYLON.Engine.SCALEMODE_CEILING:
  8634. default:
  8635. pot = Tools.CeilingPOT(value);
  8636. break;
  8637. }
  8638. return Math.min(pot, max);
  8639. };
  8640. Tools.GetFilename = function (path) {
  8641. var index = path.lastIndexOf("/");
  8642. if (index < 0)
  8643. return path;
  8644. return path.substring(index + 1);
  8645. };
  8646. /**
  8647. * Extracts the "folder" part of a path (everything before the filename).
  8648. * @param uri The URI to extract the info from
  8649. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8650. * @returns The "folder" part of the path
  8651. */
  8652. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8653. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8654. var index = uri.lastIndexOf("/");
  8655. if (index < 0) {
  8656. if (returnUnchangedIfNoSlash) {
  8657. return uri;
  8658. }
  8659. return "";
  8660. }
  8661. return uri.substring(0, index + 1);
  8662. };
  8663. Tools.GetDOMTextContent = function (element) {
  8664. var result = "";
  8665. var child = element.firstChild;
  8666. while (child) {
  8667. if (child.nodeType === 3) {
  8668. result += child.textContent;
  8669. }
  8670. child = child.nextSibling;
  8671. }
  8672. return result;
  8673. };
  8674. Tools.ToDegrees = function (angle) {
  8675. return angle * 180 / Math.PI;
  8676. };
  8677. Tools.ToRadians = function (angle) {
  8678. return angle * Math.PI / 180;
  8679. };
  8680. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8681. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8682. var output = "";
  8683. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8684. var i = 0;
  8685. var bytes = new Uint8Array(buffer);
  8686. while (i < bytes.length) {
  8687. chr1 = bytes[i++];
  8688. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8689. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8690. enc1 = chr1 >> 2;
  8691. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8692. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8693. enc4 = chr3 & 63;
  8694. if (isNaN(chr2)) {
  8695. enc3 = enc4 = 64;
  8696. }
  8697. else if (isNaN(chr3)) {
  8698. enc4 = 64;
  8699. }
  8700. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8701. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8702. }
  8703. return "data:image/png;base64," + output;
  8704. };
  8705. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8706. if (bias === void 0) { bias = null; }
  8707. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8708. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8709. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8710. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8711. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8712. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8713. }
  8714. if (bias) {
  8715. minimum.x -= minimum.x * bias.x + bias.y;
  8716. minimum.y -= minimum.y * bias.x + bias.y;
  8717. minimum.z -= minimum.z * bias.x + bias.y;
  8718. maximum.x += maximum.x * bias.x + bias.y;
  8719. maximum.y += maximum.y * bias.x + bias.y;
  8720. maximum.z += maximum.z * bias.x + bias.y;
  8721. }
  8722. return {
  8723. minimum: minimum,
  8724. maximum: maximum
  8725. };
  8726. };
  8727. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8728. if (bias === void 0) { bias = null; }
  8729. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8730. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8731. if (!stride) {
  8732. stride = 3;
  8733. }
  8734. for (var index = start; index < start + count; index++) {
  8735. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8736. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8737. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8738. }
  8739. if (bias) {
  8740. minimum.x -= minimum.x * bias.x + bias.y;
  8741. minimum.y -= minimum.y * bias.x + bias.y;
  8742. minimum.z -= minimum.z * bias.x + bias.y;
  8743. maximum.x += maximum.x * bias.x + bias.y;
  8744. maximum.y += maximum.y * bias.x + bias.y;
  8745. maximum.z += maximum.z * bias.x + bias.y;
  8746. }
  8747. return {
  8748. minimum: minimum,
  8749. maximum: maximum
  8750. };
  8751. };
  8752. Tools.Vector2ArrayFeeder = function (array) {
  8753. return function (index) {
  8754. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8755. var length = isFloatArray ? array.length / 2 : array.length;
  8756. if (index >= length) {
  8757. return null;
  8758. }
  8759. if (isFloatArray) {
  8760. var fa = array;
  8761. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8762. }
  8763. var a = array;
  8764. return a[index];
  8765. };
  8766. };
  8767. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8768. if (bias === void 0) { bias = null; }
  8769. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8770. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8771. var i = 0;
  8772. var cur = feeder(i++);
  8773. while (cur) {
  8774. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8775. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8776. cur = feeder(i++);
  8777. }
  8778. if (bias) {
  8779. minimum.x -= minimum.x * bias.x + bias.y;
  8780. minimum.y -= minimum.y * bias.x + bias.y;
  8781. maximum.x += maximum.x * bias.x + bias.y;
  8782. maximum.y += maximum.y * bias.x + bias.y;
  8783. }
  8784. return {
  8785. minimum: minimum,
  8786. maximum: maximum
  8787. };
  8788. };
  8789. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8790. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8791. return null;
  8792. return Array.isArray(obj) ? obj : [obj];
  8793. };
  8794. // Misc.
  8795. Tools.GetPointerPrefix = function () {
  8796. var eventPrefix = "pointer";
  8797. // Check if pointer events are supported
  8798. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8799. eventPrefix = "mouse";
  8800. }
  8801. return eventPrefix;
  8802. };
  8803. /**
  8804. * @param func - the function to be called
  8805. * @param requester - the object that will request the next frame. Falls back to window.
  8806. */
  8807. Tools.QueueNewFrame = function (func, requester) {
  8808. if (!Tools.IsWindowObjectExist()) {
  8809. return setTimeout(func, 16);
  8810. }
  8811. if (!requester) {
  8812. requester = window;
  8813. }
  8814. if (requester.requestAnimationFrame) {
  8815. return requester.requestAnimationFrame(func);
  8816. }
  8817. else if (requester.msRequestAnimationFrame) {
  8818. return requester.msRequestAnimationFrame(func);
  8819. }
  8820. else if (requester.webkitRequestAnimationFrame) {
  8821. return requester.webkitRequestAnimationFrame(func);
  8822. }
  8823. else if (requester.mozRequestAnimationFrame) {
  8824. return requester.mozRequestAnimationFrame(func);
  8825. }
  8826. else if (requester.oRequestAnimationFrame) {
  8827. return requester.oRequestAnimationFrame(func);
  8828. }
  8829. else {
  8830. return window.setTimeout(func, 16);
  8831. }
  8832. };
  8833. Tools.RequestFullscreen = function (element) {
  8834. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8835. if (!requestFunction)
  8836. return;
  8837. requestFunction.call(element);
  8838. };
  8839. Tools.ExitFullscreen = function () {
  8840. if (document.exitFullscreen) {
  8841. document.exitFullscreen();
  8842. }
  8843. else if (document.mozCancelFullScreen) {
  8844. document.mozCancelFullScreen();
  8845. }
  8846. else if (document.webkitCancelFullScreen) {
  8847. document.webkitCancelFullScreen();
  8848. }
  8849. else if (document.msCancelFullScreen) {
  8850. document.msCancelFullScreen();
  8851. }
  8852. };
  8853. Tools.SetCorsBehavior = function (url, element) {
  8854. if (url && url.indexOf("data:") === 0) {
  8855. return;
  8856. }
  8857. if (Tools.CorsBehavior) {
  8858. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8859. element.crossOrigin = Tools.CorsBehavior;
  8860. }
  8861. else {
  8862. var result = Tools.CorsBehavior(url);
  8863. if (result) {
  8864. element.crossOrigin = result;
  8865. }
  8866. }
  8867. }
  8868. };
  8869. // External files
  8870. Tools.CleanUrl = function (url) {
  8871. url = url.replace(/#/mg, "%23");
  8872. return url;
  8873. };
  8874. /**
  8875. * Loads an image as an HTMLImageElement.
  8876. * @param input url string, ArrayBuffer, or Blob to load
  8877. * @param onLoad callback called when the image successfully loads
  8878. * @param onError callback called when the image fails to load
  8879. * @param database database for caching
  8880. * @returns the HTMLImageElement of the loaded image
  8881. */
  8882. Tools.LoadImage = function (input, onLoad, onError, database) {
  8883. var url;
  8884. var usingObjectURL = false;
  8885. if (input instanceof ArrayBuffer) {
  8886. url = URL.createObjectURL(new Blob([input]));
  8887. usingObjectURL = true;
  8888. }
  8889. else if (input instanceof Blob) {
  8890. url = URL.createObjectURL(input);
  8891. usingObjectURL = true;
  8892. }
  8893. else {
  8894. url = Tools.CleanUrl(input);
  8895. url = Tools.PreprocessUrl(input);
  8896. }
  8897. var img = new Image();
  8898. Tools.SetCorsBehavior(url, img);
  8899. var loadHandler = function () {
  8900. if (usingObjectURL && img.src) {
  8901. URL.revokeObjectURL(img.src);
  8902. }
  8903. img.removeEventListener("load", loadHandler);
  8904. img.removeEventListener("error", errorHandler);
  8905. onLoad(img);
  8906. };
  8907. var errorHandler = function (err) {
  8908. if (usingObjectURL && img.src) {
  8909. URL.revokeObjectURL(img.src);
  8910. }
  8911. img.removeEventListener("load", loadHandler);
  8912. img.removeEventListener("error", errorHandler);
  8913. Tools.Error("Error while trying to load image: " + input);
  8914. if (onError) {
  8915. onError("Error while trying to load image: " + input, err);
  8916. }
  8917. };
  8918. img.addEventListener("load", loadHandler);
  8919. img.addEventListener("error", errorHandler);
  8920. var noIndexedDB = function () {
  8921. img.src = url;
  8922. };
  8923. var loadFromIndexedDB = function () {
  8924. if (database) {
  8925. database.loadImageFromDB(url, img);
  8926. }
  8927. };
  8928. //ANY database to do!
  8929. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8930. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8931. }
  8932. else {
  8933. if (url.indexOf("file:") !== -1) {
  8934. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8935. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8936. try {
  8937. var blobURL;
  8938. try {
  8939. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8940. }
  8941. catch (ex) {
  8942. // Chrome doesn't support oneTimeOnly parameter
  8943. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8944. }
  8945. img.src = blobURL;
  8946. usingObjectURL = true;
  8947. }
  8948. catch (e) {
  8949. img.src = "";
  8950. }
  8951. return img;
  8952. }
  8953. }
  8954. noIndexedDB();
  8955. }
  8956. return img;
  8957. };
  8958. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8959. url = Tools.CleanUrl(url);
  8960. url = Tools.PreprocessUrl(url);
  8961. // If file and file input are set
  8962. if (url.indexOf("file:") !== -1) {
  8963. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8964. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8965. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8966. }
  8967. }
  8968. var loadUrl = Tools.BaseUrl + url;
  8969. var aborted = false;
  8970. var fileRequest = {
  8971. onCompleteObservable: new BABYLON.Observable(),
  8972. abort: function () { return aborted = true; },
  8973. };
  8974. var requestFile = function () {
  8975. var request = new XMLHttpRequest();
  8976. var retryHandle = null;
  8977. fileRequest.abort = function () {
  8978. aborted = true;
  8979. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8980. request.abort();
  8981. }
  8982. if (retryHandle !== null) {
  8983. clearTimeout(retryHandle);
  8984. retryHandle = null;
  8985. }
  8986. };
  8987. var retryLoop = function (retryIndex) {
  8988. request.open('GET', loadUrl, true);
  8989. if (useArrayBuffer) {
  8990. request.responseType = "arraybuffer";
  8991. }
  8992. if (onProgress) {
  8993. request.addEventListener("progress", onProgress);
  8994. }
  8995. var onLoadEnd = function () {
  8996. request.removeEventListener("loadend", onLoadEnd);
  8997. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8998. fileRequest.onCompleteObservable.clear();
  8999. };
  9000. request.addEventListener("loadend", onLoadEnd);
  9001. var onReadyStateChange = function () {
  9002. if (aborted) {
  9003. return;
  9004. }
  9005. // In case of undefined state in some browsers.
  9006. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9007. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9008. request.removeEventListener("readystatechange", onReadyStateChange);
  9009. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9010. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9011. return;
  9012. }
  9013. var retryStrategy = Tools.DefaultRetryStrategy;
  9014. if (retryStrategy) {
  9015. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9016. if (waitTime !== -1) {
  9017. // Prevent the request from completing for retry.
  9018. request.removeEventListener("loadend", onLoadEnd);
  9019. request = new XMLHttpRequest();
  9020. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9021. return;
  9022. }
  9023. }
  9024. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9025. if (onError) {
  9026. onError(request, e);
  9027. }
  9028. else {
  9029. throw e;
  9030. }
  9031. }
  9032. };
  9033. request.addEventListener("readystatechange", onReadyStateChange);
  9034. request.send();
  9035. };
  9036. retryLoop(0);
  9037. };
  9038. // Caching all files
  9039. if (database && database.enableSceneOffline) {
  9040. var noIndexedDB_1 = function () {
  9041. if (!aborted) {
  9042. requestFile();
  9043. }
  9044. };
  9045. var loadFromIndexedDB = function () {
  9046. // TODO: database needs to support aborting and should return a IFileRequest
  9047. if (aborted) {
  9048. return;
  9049. }
  9050. if (database) {
  9051. database.loadFileFromDB(url, function (data) {
  9052. if (!aborted) {
  9053. onSuccess(data);
  9054. }
  9055. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9056. }, onProgress ? function (event) {
  9057. if (!aborted) {
  9058. onProgress(event);
  9059. }
  9060. } : undefined, noIndexedDB_1, useArrayBuffer);
  9061. }
  9062. };
  9063. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9064. }
  9065. else {
  9066. requestFile();
  9067. }
  9068. return fileRequest;
  9069. };
  9070. /**
  9071. * Load a script (identified by an url). When the url returns, the
  9072. * content of this file is added into a new script element, attached to the DOM (body element)
  9073. */
  9074. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9075. var head = document.getElementsByTagName('head')[0];
  9076. var script = document.createElement('script');
  9077. script.type = 'text/javascript';
  9078. script.src = scriptUrl;
  9079. script.onload = function () {
  9080. if (onSuccess) {
  9081. onSuccess();
  9082. }
  9083. };
  9084. script.onerror = function (e) {
  9085. if (onError) {
  9086. onError("Unable to load script '" + scriptUrl + "'", e);
  9087. }
  9088. };
  9089. head.appendChild(script);
  9090. };
  9091. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9092. var reader = new FileReader();
  9093. var request = {
  9094. onCompleteObservable: new BABYLON.Observable(),
  9095. abort: function () { return reader.abort(); },
  9096. };
  9097. reader.onloadend = function (e) {
  9098. request.onCompleteObservable.notifyObservers(request);
  9099. };
  9100. reader.onload = function (e) {
  9101. //target doesn't have result from ts 1.3
  9102. callback(e.target['result']);
  9103. };
  9104. reader.onprogress = progressCallback;
  9105. reader.readAsDataURL(fileToLoad);
  9106. return request;
  9107. };
  9108. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9109. var reader = new FileReader();
  9110. var request = {
  9111. onCompleteObservable: new BABYLON.Observable(),
  9112. abort: function () { return reader.abort(); },
  9113. };
  9114. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9115. reader.onerror = function (e) {
  9116. Tools.Log("Error while reading file: " + fileToLoad.name);
  9117. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9118. };
  9119. reader.onload = function (e) {
  9120. //target doesn't have result from ts 1.3
  9121. callback(e.target['result']);
  9122. };
  9123. if (progressCallBack) {
  9124. reader.onprogress = progressCallBack;
  9125. }
  9126. if (!useArrayBuffer) {
  9127. // Asynchronous read
  9128. reader.readAsText(fileToLoad);
  9129. }
  9130. else {
  9131. reader.readAsArrayBuffer(fileToLoad);
  9132. }
  9133. return request;
  9134. };
  9135. //returns a downloadable url to a file content.
  9136. Tools.FileAsURL = function (content) {
  9137. var fileBlob = new Blob([content]);
  9138. var url = window.URL || window.webkitURL;
  9139. var link = url.createObjectURL(fileBlob);
  9140. return link;
  9141. };
  9142. // Misc.
  9143. Tools.Format = function (value, decimals) {
  9144. if (decimals === void 0) { decimals = 2; }
  9145. return value.toFixed(decimals);
  9146. };
  9147. Tools.CheckExtends = function (v, min, max) {
  9148. if (v.x < min.x)
  9149. min.x = v.x;
  9150. if (v.y < min.y)
  9151. min.y = v.y;
  9152. if (v.z < min.z)
  9153. min.z = v.z;
  9154. if (v.x > max.x)
  9155. max.x = v.x;
  9156. if (v.y > max.y)
  9157. max.y = v.y;
  9158. if (v.z > max.z)
  9159. max.z = v.z;
  9160. };
  9161. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9162. for (var prop in source) {
  9163. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9164. continue;
  9165. }
  9166. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9167. continue;
  9168. }
  9169. var sourceValue = source[prop];
  9170. var typeOfSourceValue = typeof sourceValue;
  9171. if (typeOfSourceValue === "function") {
  9172. continue;
  9173. }
  9174. try {
  9175. if (typeOfSourceValue === "object") {
  9176. if (sourceValue instanceof Array) {
  9177. destination[prop] = [];
  9178. if (sourceValue.length > 0) {
  9179. if (typeof sourceValue[0] == "object") {
  9180. for (var index = 0; index < sourceValue.length; index++) {
  9181. var clonedValue = cloneValue(sourceValue[index], destination);
  9182. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9183. destination[prop].push(clonedValue);
  9184. }
  9185. }
  9186. }
  9187. else {
  9188. destination[prop] = sourceValue.slice(0);
  9189. }
  9190. }
  9191. }
  9192. else {
  9193. destination[prop] = cloneValue(sourceValue, destination);
  9194. }
  9195. }
  9196. else {
  9197. destination[prop] = sourceValue;
  9198. }
  9199. }
  9200. catch (e) {
  9201. // Just ignore error (it could be because of a read-only property)
  9202. }
  9203. }
  9204. };
  9205. Tools.IsEmpty = function (obj) {
  9206. for (var i in obj) {
  9207. if (obj.hasOwnProperty(i)) {
  9208. return false;
  9209. }
  9210. }
  9211. return true;
  9212. };
  9213. Tools.RegisterTopRootEvents = function (events) {
  9214. for (var index = 0; index < events.length; index++) {
  9215. var event = events[index];
  9216. window.addEventListener(event.name, event.handler, false);
  9217. try {
  9218. if (window.parent) {
  9219. window.parent.addEventListener(event.name, event.handler, false);
  9220. }
  9221. }
  9222. catch (e) {
  9223. // Silently fails...
  9224. }
  9225. }
  9226. };
  9227. Tools.UnregisterTopRootEvents = function (events) {
  9228. for (var index = 0; index < events.length; index++) {
  9229. var event = events[index];
  9230. window.removeEventListener(event.name, event.handler);
  9231. try {
  9232. if (window.parent) {
  9233. window.parent.removeEventListener(event.name, event.handler);
  9234. }
  9235. }
  9236. catch (e) {
  9237. // Silently fails...
  9238. }
  9239. }
  9240. };
  9241. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9242. if (mimeType === void 0) { mimeType = "image/png"; }
  9243. // Read the contents of the framebuffer
  9244. var numberOfChannelsByLine = width * 4;
  9245. var halfHeight = height / 2;
  9246. //Reading datas from WebGL
  9247. var data = engine.readPixels(0, 0, width, height);
  9248. //To flip image on Y axis.
  9249. for (var i = 0; i < halfHeight; i++) {
  9250. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9251. var currentCell = j + i * numberOfChannelsByLine;
  9252. var targetLine = height - i - 1;
  9253. var targetCell = j + targetLine * numberOfChannelsByLine;
  9254. var temp = data[currentCell];
  9255. data[currentCell] = data[targetCell];
  9256. data[targetCell] = temp;
  9257. }
  9258. }
  9259. // Create a 2D canvas to store the result
  9260. if (!screenshotCanvas) {
  9261. screenshotCanvas = document.createElement('canvas');
  9262. }
  9263. screenshotCanvas.width = width;
  9264. screenshotCanvas.height = height;
  9265. var context = screenshotCanvas.getContext('2d');
  9266. if (context) {
  9267. // Copy the pixels to a 2D canvas
  9268. var imageData = context.createImageData(width, height);
  9269. var castData = (imageData.data);
  9270. castData.set(data);
  9271. context.putImageData(imageData, 0, 0);
  9272. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9273. }
  9274. };
  9275. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9276. if (mimeType === void 0) { mimeType = "image/png"; }
  9277. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9278. if (successCallback) {
  9279. successCallback(base64Image);
  9280. }
  9281. else {
  9282. // We need HTMLCanvasElement.toBlob for HD screenshots
  9283. if (!screenshotCanvas.toBlob) {
  9284. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9285. screenshotCanvas.toBlob = function (callback, type, quality) {
  9286. var _this = this;
  9287. setTimeout(function () {
  9288. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9289. for (var i = 0; i < len; i++) {
  9290. arr[i] = binStr.charCodeAt(i);
  9291. }
  9292. callback(new Blob([arr], { type: type || 'image/png' }));
  9293. });
  9294. };
  9295. }
  9296. screenshotCanvas.toBlob(function (blob) {
  9297. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9298. if (("download" in document.createElement("a"))) {
  9299. if (!fileName) {
  9300. var date = new Date();
  9301. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9302. fileName = "screenshot_" + stringDate + ".png";
  9303. }
  9304. Tools.Download(blob, fileName);
  9305. }
  9306. else {
  9307. var url = URL.createObjectURL(blob);
  9308. var newWindow = window.open("");
  9309. if (!newWindow)
  9310. return;
  9311. var img = newWindow.document.createElement("img");
  9312. img.onload = function () {
  9313. // no longer need to read the blob so it's revoked
  9314. URL.revokeObjectURL(url);
  9315. };
  9316. img.src = url;
  9317. newWindow.document.body.appendChild(img);
  9318. }
  9319. });
  9320. }
  9321. };
  9322. /**
  9323. * Downloads a blob in the browser
  9324. * @param blob defines the blob to download
  9325. * @param fileName defines the name of the downloaded file
  9326. */
  9327. Tools.Download = function (blob, fileName) {
  9328. var url = window.URL.createObjectURL(blob);
  9329. var a = document.createElement("a");
  9330. document.body.appendChild(a);
  9331. a.style.display = "none";
  9332. a.href = url;
  9333. a.download = fileName;
  9334. a.addEventListener("click", function () {
  9335. if (a.parentElement) {
  9336. a.parentElement.removeChild(a);
  9337. }
  9338. });
  9339. a.click();
  9340. window.URL.revokeObjectURL(url);
  9341. };
  9342. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9343. if (mimeType === void 0) { mimeType = "image/png"; }
  9344. var width;
  9345. var height;
  9346. // If a precision value is specified
  9347. if (size.precision) {
  9348. width = Math.round(engine.getRenderWidth() * size.precision);
  9349. height = Math.round(width / engine.getAspectRatio(camera));
  9350. }
  9351. else if (size.width && size.height) {
  9352. width = size.width;
  9353. height = size.height;
  9354. }
  9355. //If passing only width, computing height to keep display canvas ratio.
  9356. else if (size.width && !size.height) {
  9357. width = size.width;
  9358. height = Math.round(width / engine.getAspectRatio(camera));
  9359. }
  9360. //If passing only height, computing width to keep display canvas ratio.
  9361. else if (size.height && !size.width) {
  9362. height = size.height;
  9363. width = Math.round(height * engine.getAspectRatio(camera));
  9364. }
  9365. //Assuming here that "size" parameter is a number
  9366. else if (!isNaN(size)) {
  9367. height = size;
  9368. width = size;
  9369. }
  9370. else {
  9371. Tools.Error("Invalid 'size' parameter !");
  9372. return;
  9373. }
  9374. if (!screenshotCanvas) {
  9375. screenshotCanvas = document.createElement('canvas');
  9376. }
  9377. screenshotCanvas.width = width;
  9378. screenshotCanvas.height = height;
  9379. var renderContext = screenshotCanvas.getContext("2d");
  9380. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9381. var newWidth = width;
  9382. var newHeight = newWidth / ratio;
  9383. if (newHeight > height) {
  9384. newHeight = height;
  9385. newWidth = newHeight * ratio;
  9386. }
  9387. var offsetX = Math.max(0, width - newWidth) / 2;
  9388. var offsetY = Math.max(0, height - newHeight) / 2;
  9389. var renderingCanvas = engine.getRenderingCanvas();
  9390. if (renderContext && renderingCanvas) {
  9391. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9392. }
  9393. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9394. };
  9395. /**
  9396. * Generates an image screenshot from the specified camera.
  9397. *
  9398. * @param engine The engine to use for rendering
  9399. * @param camera The camera to use for rendering
  9400. * @param size This parameter can be set to a single number or to an object with the
  9401. * following (optional) properties: precision, width, height. If a single number is passed,
  9402. * it will be used for both width and height. If an object is passed, the screenshot size
  9403. * will be derived from the parameters. The precision property is a multiplier allowing
  9404. * rendering at a higher or lower resolution.
  9405. * @param successCallback The callback receives a single parameter which contains the
  9406. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9407. * src parameter of an <img> to display it.
  9408. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9409. * Check your browser for supported MIME types.
  9410. * @param samples Texture samples (default: 1)
  9411. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9412. * @param fileName A name for for the downloaded file.
  9413. * @constructor
  9414. */
  9415. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9416. if (mimeType === void 0) { mimeType = "image/png"; }
  9417. if (samples === void 0) { samples = 1; }
  9418. if (antialiasing === void 0) { antialiasing = false; }
  9419. var width;
  9420. var height;
  9421. //If a precision value is specified
  9422. if (size.precision) {
  9423. width = Math.round(engine.getRenderWidth() * size.precision);
  9424. height = Math.round(width / engine.getAspectRatio(camera));
  9425. size = { width: width, height: height };
  9426. }
  9427. else if (size.width && size.height) {
  9428. width = size.width;
  9429. height = size.height;
  9430. }
  9431. //If passing only width, computing height to keep display canvas ratio.
  9432. else if (size.width && !size.height) {
  9433. width = size.width;
  9434. height = Math.round(width / engine.getAspectRatio(camera));
  9435. size = { width: width, height: height };
  9436. }
  9437. //If passing only height, computing width to keep display canvas ratio.
  9438. else if (size.height && !size.width) {
  9439. height = size.height;
  9440. width = Math.round(height * engine.getAspectRatio(camera));
  9441. size = { width: width, height: height };
  9442. }
  9443. //Assuming here that "size" parameter is a number
  9444. else if (!isNaN(size)) {
  9445. height = size;
  9446. width = size;
  9447. }
  9448. else {
  9449. Tools.Error("Invalid 'size' parameter !");
  9450. return;
  9451. }
  9452. var scene = camera.getScene();
  9453. var previousCamera = null;
  9454. if (scene.activeCamera !== camera) {
  9455. previousCamera = scene.activeCamera;
  9456. scene.activeCamera = camera;
  9457. }
  9458. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9459. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9460. texture.renderList = null;
  9461. texture.samples = samples;
  9462. if (antialiasing) {
  9463. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9464. }
  9465. texture.onAfterRenderObservable.add(function () {
  9466. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9467. });
  9468. scene.incrementRenderId();
  9469. scene.resetCachedMaterial();
  9470. texture.render(true);
  9471. texture.dispose();
  9472. if (previousCamera) {
  9473. scene.activeCamera = previousCamera;
  9474. }
  9475. camera.getProjectionMatrix(true); // Force cache refresh;
  9476. };
  9477. // XHR response validator for local file scenario
  9478. Tools.ValidateXHRData = function (xhr, dataType) {
  9479. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9480. if (dataType === void 0) { dataType = 7; }
  9481. try {
  9482. if (dataType & 1) {
  9483. if (xhr.responseText && xhr.responseText.length > 0) {
  9484. return true;
  9485. }
  9486. else if (dataType === 1) {
  9487. return false;
  9488. }
  9489. }
  9490. if (dataType & 2) {
  9491. // Check header width and height since there is no "TGA" magic number
  9492. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9493. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9494. return true;
  9495. }
  9496. else if (dataType === 2) {
  9497. return false;
  9498. }
  9499. }
  9500. if (dataType & 4) {
  9501. // Check for the "DDS" magic number
  9502. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9503. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9504. return true;
  9505. }
  9506. else {
  9507. return false;
  9508. }
  9509. }
  9510. }
  9511. catch (e) {
  9512. // Global protection
  9513. }
  9514. return false;
  9515. };
  9516. /**
  9517. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9518. * Be aware Math.random() could cause collisions, but:
  9519. * "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"
  9520. */
  9521. Tools.RandomId = function () {
  9522. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9523. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9524. return v.toString(16);
  9525. });
  9526. };
  9527. /**
  9528. * Test if the given uri is a base64 string.
  9529. * @param uri The uri to test
  9530. * @return True if the uri is a base64 string or false otherwise.
  9531. */
  9532. Tools.IsBase64 = function (uri) {
  9533. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9534. };
  9535. /**
  9536. * Decode the given base64 uri.
  9537. * @param uri The uri to decode
  9538. * @return The decoded base64 data.
  9539. */
  9540. Tools.DecodeBase64 = function (uri) {
  9541. var decodedString = atob(uri.split(",")[1]);
  9542. var bufferLength = decodedString.length;
  9543. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9544. for (var i = 0; i < bufferLength; i++) {
  9545. bufferView[i] = decodedString.charCodeAt(i);
  9546. }
  9547. return bufferView.buffer;
  9548. };
  9549. Object.defineProperty(Tools, "NoneLogLevel", {
  9550. get: function () {
  9551. return Tools._NoneLogLevel;
  9552. },
  9553. enumerable: true,
  9554. configurable: true
  9555. });
  9556. Object.defineProperty(Tools, "MessageLogLevel", {
  9557. get: function () {
  9558. return Tools._MessageLogLevel;
  9559. },
  9560. enumerable: true,
  9561. configurable: true
  9562. });
  9563. Object.defineProperty(Tools, "WarningLogLevel", {
  9564. get: function () {
  9565. return Tools._WarningLogLevel;
  9566. },
  9567. enumerable: true,
  9568. configurable: true
  9569. });
  9570. Object.defineProperty(Tools, "ErrorLogLevel", {
  9571. get: function () {
  9572. return Tools._ErrorLogLevel;
  9573. },
  9574. enumerable: true,
  9575. configurable: true
  9576. });
  9577. Object.defineProperty(Tools, "AllLogLevel", {
  9578. get: function () {
  9579. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9580. },
  9581. enumerable: true,
  9582. configurable: true
  9583. });
  9584. Tools._AddLogEntry = function (entry) {
  9585. Tools._LogCache = entry + Tools._LogCache;
  9586. if (Tools.OnNewCacheEntry) {
  9587. Tools.OnNewCacheEntry(entry);
  9588. }
  9589. };
  9590. Tools._FormatMessage = function (message) {
  9591. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9592. var date = new Date();
  9593. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9594. };
  9595. Tools._LogDisabled = function (message) {
  9596. // nothing to do
  9597. };
  9598. Tools._LogEnabled = function (message) {
  9599. var formattedMessage = Tools._FormatMessage(message);
  9600. console.log("BJS - " + formattedMessage);
  9601. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9602. Tools._AddLogEntry(entry);
  9603. };
  9604. Tools._WarnDisabled = function (message) {
  9605. // nothing to do
  9606. };
  9607. Tools._WarnEnabled = function (message) {
  9608. var formattedMessage = Tools._FormatMessage(message);
  9609. console.warn("BJS - " + formattedMessage);
  9610. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9611. Tools._AddLogEntry(entry);
  9612. };
  9613. Tools._ErrorDisabled = function (message) {
  9614. // nothing to do
  9615. };
  9616. Tools._ErrorEnabled = function (message) {
  9617. Tools.errorsCount++;
  9618. var formattedMessage = Tools._FormatMessage(message);
  9619. console.error("BJS - " + formattedMessage);
  9620. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9621. Tools._AddLogEntry(entry);
  9622. };
  9623. Object.defineProperty(Tools, "LogCache", {
  9624. get: function () {
  9625. return Tools._LogCache;
  9626. },
  9627. enumerable: true,
  9628. configurable: true
  9629. });
  9630. Tools.ClearLogCache = function () {
  9631. Tools._LogCache = "";
  9632. Tools.errorsCount = 0;
  9633. };
  9634. Object.defineProperty(Tools, "LogLevels", {
  9635. set: function (level) {
  9636. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9637. Tools.Log = Tools._LogEnabled;
  9638. }
  9639. else {
  9640. Tools.Log = Tools._LogDisabled;
  9641. }
  9642. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9643. Tools.Warn = Tools._WarnEnabled;
  9644. }
  9645. else {
  9646. Tools.Warn = Tools._WarnDisabled;
  9647. }
  9648. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9649. Tools.Error = Tools._ErrorEnabled;
  9650. }
  9651. else {
  9652. Tools.Error = Tools._ErrorDisabled;
  9653. }
  9654. },
  9655. enumerable: true,
  9656. configurable: true
  9657. });
  9658. Tools.IsWindowObjectExist = function () {
  9659. return (typeof window) !== "undefined";
  9660. };
  9661. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9662. get: function () {
  9663. return Tools._PerformanceNoneLogLevel;
  9664. },
  9665. enumerable: true,
  9666. configurable: true
  9667. });
  9668. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9669. get: function () {
  9670. return Tools._PerformanceUserMarkLogLevel;
  9671. },
  9672. enumerable: true,
  9673. configurable: true
  9674. });
  9675. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9676. get: function () {
  9677. return Tools._PerformanceConsoleLogLevel;
  9678. },
  9679. enumerable: true,
  9680. configurable: true
  9681. });
  9682. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9683. set: function (level) {
  9684. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9685. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9686. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9687. return;
  9688. }
  9689. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9690. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9691. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9692. return;
  9693. }
  9694. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9695. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9696. },
  9697. enumerable: true,
  9698. configurable: true
  9699. });
  9700. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9701. };
  9702. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9703. };
  9704. Tools._StartUserMark = function (counterName, condition) {
  9705. if (condition === void 0) { condition = true; }
  9706. if (!Tools._performance) {
  9707. if (!Tools.IsWindowObjectExist()) {
  9708. return;
  9709. }
  9710. Tools._performance = window.performance;
  9711. }
  9712. if (!condition || !Tools._performance.mark) {
  9713. return;
  9714. }
  9715. Tools._performance.mark(counterName + "-Begin");
  9716. };
  9717. Tools._EndUserMark = function (counterName, condition) {
  9718. if (condition === void 0) { condition = true; }
  9719. if (!condition || !Tools._performance.mark) {
  9720. return;
  9721. }
  9722. Tools._performance.mark(counterName + "-End");
  9723. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9724. };
  9725. Tools._StartPerformanceConsole = function (counterName, condition) {
  9726. if (condition === void 0) { condition = true; }
  9727. if (!condition) {
  9728. return;
  9729. }
  9730. Tools._StartUserMark(counterName, condition);
  9731. if (console.time) {
  9732. console.time(counterName);
  9733. }
  9734. };
  9735. Tools._EndPerformanceConsole = function (counterName, condition) {
  9736. if (condition === void 0) { condition = true; }
  9737. if (!condition) {
  9738. return;
  9739. }
  9740. Tools._EndUserMark(counterName, condition);
  9741. if (console.time) {
  9742. console.timeEnd(counterName);
  9743. }
  9744. };
  9745. Object.defineProperty(Tools, "Now", {
  9746. get: function () {
  9747. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9748. return window.performance.now();
  9749. }
  9750. return Date.now();
  9751. },
  9752. enumerable: true,
  9753. configurable: true
  9754. });
  9755. /**
  9756. * This method will return the name of the class used to create the instance of the given object.
  9757. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9758. * @param object the object to get the class name from
  9759. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9760. */
  9761. Tools.GetClassName = function (object, isType) {
  9762. if (isType === void 0) { isType = false; }
  9763. var name = null;
  9764. if (!isType && object.getClassName) {
  9765. name = object.getClassName();
  9766. }
  9767. else {
  9768. if (object instanceof Object) {
  9769. var classObj = isType ? object : Object.getPrototypeOf(object);
  9770. name = classObj.constructor["__bjsclassName__"];
  9771. }
  9772. if (!name) {
  9773. name = typeof object;
  9774. }
  9775. }
  9776. return name;
  9777. };
  9778. Tools.First = function (array, predicate) {
  9779. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9780. var el = array_1[_i];
  9781. if (predicate(el)) {
  9782. return el;
  9783. }
  9784. }
  9785. return null;
  9786. };
  9787. /**
  9788. * This method will return the name of the full name of the class, including its owning module (if any).
  9789. * 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).
  9790. * @param object the object to get the class name from
  9791. * @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.
  9792. */
  9793. Tools.getFullClassName = function (object, isType) {
  9794. if (isType === void 0) { isType = false; }
  9795. var className = null;
  9796. var moduleName = null;
  9797. if (!isType && object.getClassName) {
  9798. className = object.getClassName();
  9799. }
  9800. else {
  9801. if (object instanceof Object) {
  9802. var classObj = isType ? object : Object.getPrototypeOf(object);
  9803. className = classObj.constructor["__bjsclassName__"];
  9804. moduleName = classObj.constructor["__bjsmoduleName__"];
  9805. }
  9806. if (!className) {
  9807. className = typeof object;
  9808. }
  9809. }
  9810. if (!className) {
  9811. return null;
  9812. }
  9813. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9814. };
  9815. /**
  9816. * 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.
  9817. * @param array
  9818. */
  9819. Tools.arrayOrStringFeeder = function (array) {
  9820. return function (index) {
  9821. if (index >= array.length) {
  9822. return null;
  9823. }
  9824. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9825. if (val && val.getHashCode) {
  9826. val = val.getHashCode();
  9827. }
  9828. if (typeof val === "string") {
  9829. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9830. }
  9831. return val;
  9832. };
  9833. };
  9834. /**
  9835. * Compute the hashCode of a stream of number
  9836. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9837. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9838. * @return the hash code computed
  9839. */
  9840. Tools.hashCodeFromStream = function (feeder) {
  9841. // Based from here: http://stackoverflow.com/a/7616484/802124
  9842. var hash = 0;
  9843. var index = 0;
  9844. var chr = feeder(index++);
  9845. while (chr != null) {
  9846. hash = ((hash << 5) - hash) + chr;
  9847. hash |= 0; // Convert to 32bit integer
  9848. chr = feeder(index++);
  9849. }
  9850. return hash;
  9851. };
  9852. /**
  9853. * Returns a promise that resolves after the given amount of time.
  9854. * @param delay Number of milliseconds to delay
  9855. * @returns Promise that resolves after the given amount of time
  9856. */
  9857. Tools.DelayAsync = function (delay) {
  9858. return new Promise(function (resolve) {
  9859. setTimeout(function () {
  9860. resolve();
  9861. }, delay);
  9862. });
  9863. };
  9864. Tools.BaseUrl = "";
  9865. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9866. /**
  9867. * Default behaviour for cors in the application.
  9868. * It can be a string if the expected behavior is identical in the entire app.
  9869. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9870. */
  9871. Tools.CorsBehavior = "anonymous";
  9872. Tools.UseFallbackTexture = true;
  9873. /**
  9874. * Use this object to register external classes like custom textures or material
  9875. * to allow the laoders to instantiate them
  9876. */
  9877. Tools.RegisteredExternalClasses = {};
  9878. // Used in case of a texture loading problem
  9879. 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";
  9880. Tools._tmpFloatArray = new Float32Array(1);
  9881. Tools.PreprocessUrl = function (url) {
  9882. return url;
  9883. };
  9884. // Logs
  9885. Tools._NoneLogLevel = 0;
  9886. Tools._MessageLogLevel = 1;
  9887. Tools._WarningLogLevel = 2;
  9888. Tools._ErrorLogLevel = 4;
  9889. Tools._LogCache = "";
  9890. Tools.errorsCount = 0;
  9891. Tools.Log = Tools._LogEnabled;
  9892. Tools.Warn = Tools._WarnEnabled;
  9893. Tools.Error = Tools._ErrorEnabled;
  9894. // Performances
  9895. Tools._PerformanceNoneLogLevel = 0;
  9896. Tools._PerformanceUserMarkLogLevel = 1;
  9897. Tools._PerformanceConsoleLogLevel = 2;
  9898. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9899. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9900. return Tools;
  9901. }());
  9902. BABYLON.Tools = Tools;
  9903. /**
  9904. * This class is used to track a performance counter which is number based.
  9905. * The user has access to many properties which give statistics of different nature
  9906. *
  9907. * The implementer can track two kinds of Performance Counter: time and count
  9908. * 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.
  9909. * 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.
  9910. */
  9911. var PerfCounter = /** @class */ (function () {
  9912. function PerfCounter() {
  9913. this._startMonitoringTime = 0;
  9914. this._min = 0;
  9915. this._max = 0;
  9916. this._average = 0;
  9917. this._lastSecAverage = 0;
  9918. this._current = 0;
  9919. this._totalValueCount = 0;
  9920. this._totalAccumulated = 0;
  9921. this._lastSecAccumulated = 0;
  9922. this._lastSecTime = 0;
  9923. this._lastSecValueCount = 0;
  9924. }
  9925. Object.defineProperty(PerfCounter.prototype, "min", {
  9926. /**
  9927. * Returns the smallest value ever
  9928. */
  9929. get: function () {
  9930. return this._min;
  9931. },
  9932. enumerable: true,
  9933. configurable: true
  9934. });
  9935. Object.defineProperty(PerfCounter.prototype, "max", {
  9936. /**
  9937. * Returns the biggest value ever
  9938. */
  9939. get: function () {
  9940. return this._max;
  9941. },
  9942. enumerable: true,
  9943. configurable: true
  9944. });
  9945. Object.defineProperty(PerfCounter.prototype, "average", {
  9946. /**
  9947. * Returns the average value since the performance counter is running
  9948. */
  9949. get: function () {
  9950. return this._average;
  9951. },
  9952. enumerable: true,
  9953. configurable: true
  9954. });
  9955. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9956. /**
  9957. * Returns the average value of the last second the counter was monitored
  9958. */
  9959. get: function () {
  9960. return this._lastSecAverage;
  9961. },
  9962. enumerable: true,
  9963. configurable: true
  9964. });
  9965. Object.defineProperty(PerfCounter.prototype, "current", {
  9966. /**
  9967. * Returns the current value
  9968. */
  9969. get: function () {
  9970. return this._current;
  9971. },
  9972. enumerable: true,
  9973. configurable: true
  9974. });
  9975. Object.defineProperty(PerfCounter.prototype, "total", {
  9976. get: function () {
  9977. return this._totalAccumulated;
  9978. },
  9979. enumerable: true,
  9980. configurable: true
  9981. });
  9982. Object.defineProperty(PerfCounter.prototype, "count", {
  9983. get: function () {
  9984. return this._totalValueCount;
  9985. },
  9986. enumerable: true,
  9987. configurable: true
  9988. });
  9989. /**
  9990. * Call this method to start monitoring a new frame.
  9991. * 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.
  9992. */
  9993. PerfCounter.prototype.fetchNewFrame = function () {
  9994. this._totalValueCount++;
  9995. this._current = 0;
  9996. this._lastSecValueCount++;
  9997. };
  9998. /**
  9999. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10000. * @param newCount the count value to add to the monitored count
  10001. * @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.
  10002. */
  10003. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10004. if (!PerfCounter.Enabled) {
  10005. return;
  10006. }
  10007. this._current += newCount;
  10008. if (fetchResult) {
  10009. this._fetchResult();
  10010. }
  10011. };
  10012. /**
  10013. * Start monitoring this performance counter
  10014. */
  10015. PerfCounter.prototype.beginMonitoring = function () {
  10016. if (!PerfCounter.Enabled) {
  10017. return;
  10018. }
  10019. this._startMonitoringTime = Tools.Now;
  10020. };
  10021. /**
  10022. * Compute the time lapsed since the previous beginMonitoring() call.
  10023. * @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
  10024. */
  10025. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10026. if (newFrame === void 0) { newFrame = true; }
  10027. if (!PerfCounter.Enabled) {
  10028. return;
  10029. }
  10030. if (newFrame) {
  10031. this.fetchNewFrame();
  10032. }
  10033. var currentTime = Tools.Now;
  10034. this._current = currentTime - this._startMonitoringTime;
  10035. if (newFrame) {
  10036. this._fetchResult();
  10037. }
  10038. };
  10039. PerfCounter.prototype._fetchResult = function () {
  10040. this._totalAccumulated += this._current;
  10041. this._lastSecAccumulated += this._current;
  10042. // Min/Max update
  10043. this._min = Math.min(this._min, this._current);
  10044. this._max = Math.max(this._max, this._current);
  10045. this._average = this._totalAccumulated / this._totalValueCount;
  10046. // Reset last sec?
  10047. var now = Tools.Now;
  10048. if ((now - this._lastSecTime) > 1000) {
  10049. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10050. this._lastSecTime = now;
  10051. this._lastSecAccumulated = 0;
  10052. this._lastSecValueCount = 0;
  10053. }
  10054. };
  10055. PerfCounter.Enabled = true;
  10056. return PerfCounter;
  10057. }());
  10058. BABYLON.PerfCounter = PerfCounter;
  10059. /**
  10060. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10061. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10062. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10063. * @param name The name of the class, case should be preserved
  10064. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10065. */
  10066. function className(name, module) {
  10067. return function (target) {
  10068. target["__bjsclassName__"] = name;
  10069. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10070. };
  10071. }
  10072. BABYLON.className = className;
  10073. /**
  10074. * An implementation of a loop for asynchronous functions.
  10075. */
  10076. var AsyncLoop = /** @class */ (function () {
  10077. /**
  10078. * Constroctor.
  10079. * @param iterations the number of iterations.
  10080. * @param _fn the function to run each iteration
  10081. * @param _successCallback the callback that will be called upon succesful execution
  10082. * @param offset starting offset.
  10083. */
  10084. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10085. if (offset === void 0) { offset = 0; }
  10086. this.iterations = iterations;
  10087. this._fn = _fn;
  10088. this._successCallback = _successCallback;
  10089. this.index = offset - 1;
  10090. this._done = false;
  10091. }
  10092. /**
  10093. * Execute the next iteration. Must be called after the last iteration was finished.
  10094. */
  10095. AsyncLoop.prototype.executeNext = function () {
  10096. if (!this._done) {
  10097. if (this.index + 1 < this.iterations) {
  10098. ++this.index;
  10099. this._fn(this);
  10100. }
  10101. else {
  10102. this.breakLoop();
  10103. }
  10104. }
  10105. };
  10106. /**
  10107. * Break the loop and run the success callback.
  10108. */
  10109. AsyncLoop.prototype.breakLoop = function () {
  10110. this._done = true;
  10111. this._successCallback();
  10112. };
  10113. /**
  10114. * Helper function
  10115. */
  10116. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10117. if (offset === void 0) { offset = 0; }
  10118. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10119. loop.executeNext();
  10120. return loop;
  10121. };
  10122. /**
  10123. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10124. * @param iterations total number of iterations
  10125. * @param syncedIterations number of synchronous iterations in each async iteration.
  10126. * @param fn the function to call each iteration.
  10127. * @param callback a success call back that will be called when iterating stops.
  10128. * @param breakFunction a break condition (optional)
  10129. * @param timeout timeout settings for the setTimeout function. default - 0.
  10130. * @constructor
  10131. */
  10132. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10133. if (timeout === void 0) { timeout = 0; }
  10134. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10135. if (breakFunction && breakFunction())
  10136. loop.breakLoop();
  10137. else {
  10138. setTimeout(function () {
  10139. for (var i = 0; i < syncedIterations; ++i) {
  10140. var iteration = (loop.index * syncedIterations) + i;
  10141. if (iteration >= iterations)
  10142. break;
  10143. fn(iteration);
  10144. if (breakFunction && breakFunction()) {
  10145. loop.breakLoop();
  10146. break;
  10147. }
  10148. }
  10149. loop.executeNext();
  10150. }, timeout);
  10151. }
  10152. }, callback);
  10153. };
  10154. return AsyncLoop;
  10155. }());
  10156. BABYLON.AsyncLoop = AsyncLoop;
  10157. })(BABYLON || (BABYLON = {}));
  10158. //# sourceMappingURL=babylon.tools.js.map
  10159. var BABYLON;
  10160. (function (BABYLON) {
  10161. var PromiseStates;
  10162. (function (PromiseStates) {
  10163. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10164. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10165. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10166. })(PromiseStates || (PromiseStates = {}));
  10167. var FulFillmentAgregator = /** @class */ (function () {
  10168. function FulFillmentAgregator() {
  10169. this.count = 0;
  10170. this.target = 0;
  10171. this.results = [];
  10172. }
  10173. return FulFillmentAgregator;
  10174. }());
  10175. var InternalPromise = /** @class */ (function () {
  10176. function InternalPromise(resolver) {
  10177. var _this = this;
  10178. this._state = PromiseStates.Pending;
  10179. this._children = new Array();
  10180. this._rejectWasConsumed = false;
  10181. if (!resolver) {
  10182. return;
  10183. }
  10184. try {
  10185. resolver(function (value) {
  10186. _this._resolve(value);
  10187. }, function (reason) {
  10188. _this._reject(reason);
  10189. });
  10190. }
  10191. catch (e) {
  10192. this._reject(e);
  10193. }
  10194. }
  10195. Object.defineProperty(InternalPromise.prototype, "_result", {
  10196. get: function () {
  10197. return this._resultValue;
  10198. },
  10199. set: function (value) {
  10200. this._resultValue = value;
  10201. if (this._parent && this._parent._result === undefined) {
  10202. this._parent._result = value;
  10203. }
  10204. },
  10205. enumerable: true,
  10206. configurable: true
  10207. });
  10208. InternalPromise.prototype.catch = function (onRejected) {
  10209. return this.then(undefined, onRejected);
  10210. };
  10211. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10212. var _this = this;
  10213. var newPromise = new InternalPromise();
  10214. newPromise._onFulfilled = onFulfilled;
  10215. newPromise._onRejected = onRejected;
  10216. // Composition
  10217. this._children.push(newPromise);
  10218. newPromise._parent = this;
  10219. if (this._state !== PromiseStates.Pending) {
  10220. BABYLON.Tools.SetImmediate(function () {
  10221. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10222. var returnedValue = newPromise._resolve(_this._result);
  10223. if (returnedValue !== undefined && returnedValue !== null) {
  10224. if (returnedValue._state !== undefined) {
  10225. var returnedPromise = returnedValue;
  10226. newPromise._children.push(returnedPromise);
  10227. returnedPromise._parent = newPromise;
  10228. newPromise = returnedPromise;
  10229. }
  10230. else {
  10231. newPromise._result = returnedValue;
  10232. }
  10233. }
  10234. }
  10235. else {
  10236. newPromise._reject(_this._reason);
  10237. }
  10238. });
  10239. }
  10240. return newPromise;
  10241. };
  10242. InternalPromise.prototype._moveChildren = function (children) {
  10243. var _this = this;
  10244. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10245. this._children.forEach(function (child) {
  10246. child._parent = _this;
  10247. });
  10248. if (this._state === PromiseStates.Fulfilled) {
  10249. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10250. var child = _b[_i];
  10251. child._resolve(this._result);
  10252. }
  10253. }
  10254. else if (this._state === PromiseStates.Rejected) {
  10255. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10256. var child = _d[_c];
  10257. child._reject(this._reason);
  10258. }
  10259. }
  10260. var _a;
  10261. };
  10262. InternalPromise.prototype._resolve = function (value) {
  10263. try {
  10264. this._state = PromiseStates.Fulfilled;
  10265. var returnedValue = null;
  10266. if (this._onFulfilled) {
  10267. returnedValue = this._onFulfilled(value);
  10268. }
  10269. if (returnedValue !== undefined && returnedValue !== null) {
  10270. if (returnedValue._state !== undefined) {
  10271. // Transmit children
  10272. var returnedPromise = returnedValue;
  10273. returnedPromise._parent = this;
  10274. returnedPromise._moveChildren(this._children);
  10275. value = returnedPromise._result;
  10276. }
  10277. else {
  10278. value = returnedValue;
  10279. }
  10280. }
  10281. this._result = value;
  10282. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10283. var child = _a[_i];
  10284. child._resolve(value);
  10285. }
  10286. this._children.length = 0;
  10287. delete this._onFulfilled;
  10288. delete this._onRejected;
  10289. }
  10290. catch (e) {
  10291. this._reject(e, true);
  10292. }
  10293. };
  10294. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10295. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10296. this._state = PromiseStates.Rejected;
  10297. this._reason = reason;
  10298. if (this._onRejected && !onLocalThrow) {
  10299. try {
  10300. this._onRejected(reason);
  10301. this._rejectWasConsumed = true;
  10302. }
  10303. catch (e) {
  10304. reason = e;
  10305. }
  10306. }
  10307. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10308. var child = _a[_i];
  10309. if (this._rejectWasConsumed) {
  10310. child._resolve(null);
  10311. }
  10312. else {
  10313. child._reject(reason);
  10314. }
  10315. }
  10316. this._children.length = 0;
  10317. delete this._onFulfilled;
  10318. delete this._onRejected;
  10319. };
  10320. InternalPromise.resolve = function (value) {
  10321. var newPromise = new InternalPromise();
  10322. newPromise._resolve(value);
  10323. return newPromise;
  10324. };
  10325. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10326. promise.then(function (value) {
  10327. agregator.results[index] = value;
  10328. agregator.count++;
  10329. if (agregator.count === agregator.target) {
  10330. agregator.rootPromise._resolve(agregator.results);
  10331. }
  10332. return null;
  10333. }, function (reason) {
  10334. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10335. agregator.rootPromise._reject(reason);
  10336. }
  10337. });
  10338. };
  10339. InternalPromise.all = function (promises) {
  10340. var newPromise = new InternalPromise();
  10341. var agregator = new FulFillmentAgregator();
  10342. agregator.target = promises.length;
  10343. agregator.rootPromise = newPromise;
  10344. if (promises.length) {
  10345. for (var index = 0; index < promises.length; index++) {
  10346. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10347. }
  10348. }
  10349. else {
  10350. newPromise._resolve([]);
  10351. }
  10352. return newPromise;
  10353. };
  10354. InternalPromise.race = function (promises) {
  10355. var newPromise = new InternalPromise();
  10356. if (promises.length) {
  10357. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10358. var promise = promises_1[_i];
  10359. promise.then(function (value) {
  10360. if (newPromise) {
  10361. newPromise._resolve(value);
  10362. newPromise = null;
  10363. }
  10364. return null;
  10365. }, function (reason) {
  10366. if (newPromise) {
  10367. newPromise._reject(reason);
  10368. newPromise = null;
  10369. }
  10370. });
  10371. }
  10372. }
  10373. return newPromise;
  10374. };
  10375. return InternalPromise;
  10376. }());
  10377. /**
  10378. * Helper class that provides a small promise polyfill
  10379. */
  10380. var PromisePolyfill = /** @class */ (function () {
  10381. function PromisePolyfill() {
  10382. }
  10383. /**
  10384. * Static function used to check if the polyfill is required
  10385. * If this is the case then the function will inject the polyfill to window.Promise
  10386. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10387. */
  10388. PromisePolyfill.Apply = function (force) {
  10389. if (force === void 0) { force = false; }
  10390. if (force || typeof Promise === 'undefined') {
  10391. var root = window;
  10392. root.Promise = InternalPromise;
  10393. }
  10394. };
  10395. return PromisePolyfill;
  10396. }());
  10397. BABYLON.PromisePolyfill = PromisePolyfill;
  10398. })(BABYLON || (BABYLON = {}));
  10399. //# sourceMappingURL=babylon.promise.js.map
  10400. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10401. var BABYLON;
  10402. (function (BABYLON) {
  10403. /**
  10404. * Helper class to push actions to a pool of workers.
  10405. */
  10406. var WorkerPool = /** @class */ (function () {
  10407. /**
  10408. * Constructor
  10409. * @param workers Array of workers to use for actions
  10410. */
  10411. function WorkerPool(workers) {
  10412. this._pendingActions = new Array();
  10413. this._workerInfos = workers.map(function (worker) { return ({
  10414. worker: worker,
  10415. active: false
  10416. }); });
  10417. }
  10418. /**
  10419. * Terminates all workers and clears any pending actions.
  10420. */
  10421. WorkerPool.prototype.dispose = function () {
  10422. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10423. var workerInfo = _a[_i];
  10424. workerInfo.worker.terminate();
  10425. }
  10426. delete this._workerInfos;
  10427. delete this._pendingActions;
  10428. };
  10429. /**
  10430. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10431. * pended until a worker has completed its action.
  10432. * @param action The action to perform. Call onComplete when the action is complete.
  10433. */
  10434. WorkerPool.prototype.push = function (action) {
  10435. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10436. var workerInfo = _a[_i];
  10437. if (!workerInfo.active) {
  10438. this._execute(workerInfo, action);
  10439. return;
  10440. }
  10441. }
  10442. this._pendingActions.push(action);
  10443. };
  10444. WorkerPool.prototype._execute = function (workerInfo, action) {
  10445. var _this = this;
  10446. workerInfo.active = true;
  10447. action(workerInfo.worker, function () {
  10448. workerInfo.active = false;
  10449. var nextAction = _this._pendingActions.shift();
  10450. if (nextAction) {
  10451. _this._execute(workerInfo, nextAction);
  10452. }
  10453. });
  10454. };
  10455. return WorkerPool;
  10456. }());
  10457. BABYLON.WorkerPool = WorkerPool;
  10458. })(BABYLON || (BABYLON = {}));
  10459. //# sourceMappingURL=babylon.workerPool.js.map
  10460. var BABYLON;
  10461. (function (BABYLON) {
  10462. /**
  10463. * @hidden
  10464. **/
  10465. var _AlphaState = /** @class */ (function () {
  10466. /**
  10467. * Initializes the state.
  10468. */
  10469. function _AlphaState() {
  10470. this._isAlphaBlendDirty = false;
  10471. this._isBlendFunctionParametersDirty = false;
  10472. this._isBlendEquationParametersDirty = false;
  10473. this._isBlendConstantsDirty = false;
  10474. this._alphaBlend = false;
  10475. this._blendFunctionParameters = new Array(4);
  10476. this._blendEquationParameters = new Array(2);
  10477. this._blendConstants = new Array(4);
  10478. this.reset();
  10479. }
  10480. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10481. get: function () {
  10482. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10483. },
  10484. enumerable: true,
  10485. configurable: true
  10486. });
  10487. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10488. get: function () {
  10489. return this._alphaBlend;
  10490. },
  10491. set: function (value) {
  10492. if (this._alphaBlend === value) {
  10493. return;
  10494. }
  10495. this._alphaBlend = value;
  10496. this._isAlphaBlendDirty = true;
  10497. },
  10498. enumerable: true,
  10499. configurable: true
  10500. });
  10501. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10502. if (this._blendConstants[0] === r &&
  10503. this._blendConstants[1] === g &&
  10504. this._blendConstants[2] === b &&
  10505. this._blendConstants[3] === a) {
  10506. return;
  10507. }
  10508. this._blendConstants[0] = r;
  10509. this._blendConstants[1] = g;
  10510. this._blendConstants[2] = b;
  10511. this._blendConstants[3] = a;
  10512. this._isBlendConstantsDirty = true;
  10513. };
  10514. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10515. if (this._blendFunctionParameters[0] === value0 &&
  10516. this._blendFunctionParameters[1] === value1 &&
  10517. this._blendFunctionParameters[2] === value2 &&
  10518. this._blendFunctionParameters[3] === value3) {
  10519. return;
  10520. }
  10521. this._blendFunctionParameters[0] = value0;
  10522. this._blendFunctionParameters[1] = value1;
  10523. this._blendFunctionParameters[2] = value2;
  10524. this._blendFunctionParameters[3] = value3;
  10525. this._isBlendFunctionParametersDirty = true;
  10526. };
  10527. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10528. if (this._blendEquationParameters[0] === rgb &&
  10529. this._blendEquationParameters[1] === alpha) {
  10530. return;
  10531. }
  10532. this._blendEquationParameters[0] = rgb;
  10533. this._blendEquationParameters[1] = alpha;
  10534. this._isBlendEquationParametersDirty = true;
  10535. };
  10536. _AlphaState.prototype.reset = function () {
  10537. this._alphaBlend = false;
  10538. this._blendFunctionParameters[0] = null;
  10539. this._blendFunctionParameters[1] = null;
  10540. this._blendFunctionParameters[2] = null;
  10541. this._blendFunctionParameters[3] = null;
  10542. this._blendEquationParameters[0] = null;
  10543. this._blendEquationParameters[1] = null;
  10544. this._blendConstants[0] = null;
  10545. this._blendConstants[1] = null;
  10546. this._blendConstants[2] = null;
  10547. this._blendConstants[3] = null;
  10548. this._isAlphaBlendDirty = true;
  10549. this._isBlendFunctionParametersDirty = false;
  10550. this._isBlendEquationParametersDirty = false;
  10551. this._isBlendConstantsDirty = false;
  10552. };
  10553. _AlphaState.prototype.apply = function (gl) {
  10554. if (!this.isDirty) {
  10555. return;
  10556. }
  10557. // Alpha blend
  10558. if (this._isAlphaBlendDirty) {
  10559. if (this._alphaBlend) {
  10560. gl.enable(gl.BLEND);
  10561. }
  10562. else {
  10563. gl.disable(gl.BLEND);
  10564. }
  10565. this._isAlphaBlendDirty = false;
  10566. }
  10567. // Alpha function
  10568. if (this._isBlendFunctionParametersDirty) {
  10569. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10570. this._isBlendFunctionParametersDirty = false;
  10571. }
  10572. // Alpha equation
  10573. if (this._isBlendEquationParametersDirty) {
  10574. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10575. this._isBlendEquationParametersDirty = false;
  10576. }
  10577. // Constants
  10578. if (this._isBlendConstantsDirty) {
  10579. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10580. this._isBlendConstantsDirty = false;
  10581. }
  10582. };
  10583. return _AlphaState;
  10584. }());
  10585. BABYLON._AlphaState = _AlphaState;
  10586. })(BABYLON || (BABYLON = {}));
  10587. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10588. var BABYLON;
  10589. (function (BABYLON) {
  10590. /**
  10591. * @hidden
  10592. **/
  10593. var _DepthCullingState = /** @class */ (function () {
  10594. /**
  10595. * Initializes the state.
  10596. */
  10597. function _DepthCullingState() {
  10598. this._isDepthTestDirty = false;
  10599. this._isDepthMaskDirty = false;
  10600. this._isDepthFuncDirty = false;
  10601. this._isCullFaceDirty = false;
  10602. this._isCullDirty = false;
  10603. this._isZOffsetDirty = false;
  10604. this._isFrontFaceDirty = false;
  10605. this.reset();
  10606. }
  10607. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10608. get: function () {
  10609. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10610. },
  10611. enumerable: true,
  10612. configurable: true
  10613. });
  10614. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10615. get: function () {
  10616. return this._zOffset;
  10617. },
  10618. set: function (value) {
  10619. if (this._zOffset === value) {
  10620. return;
  10621. }
  10622. this._zOffset = value;
  10623. this._isZOffsetDirty = true;
  10624. },
  10625. enumerable: true,
  10626. configurable: true
  10627. });
  10628. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10629. get: function () {
  10630. return this._cullFace;
  10631. },
  10632. set: function (value) {
  10633. if (this._cullFace === value) {
  10634. return;
  10635. }
  10636. this._cullFace = value;
  10637. this._isCullFaceDirty = true;
  10638. },
  10639. enumerable: true,
  10640. configurable: true
  10641. });
  10642. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10643. get: function () {
  10644. return this._cull;
  10645. },
  10646. set: function (value) {
  10647. if (this._cull === value) {
  10648. return;
  10649. }
  10650. this._cull = value;
  10651. this._isCullDirty = true;
  10652. },
  10653. enumerable: true,
  10654. configurable: true
  10655. });
  10656. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10657. get: function () {
  10658. return this._depthFunc;
  10659. },
  10660. set: function (value) {
  10661. if (this._depthFunc === value) {
  10662. return;
  10663. }
  10664. this._depthFunc = value;
  10665. this._isDepthFuncDirty = true;
  10666. },
  10667. enumerable: true,
  10668. configurable: true
  10669. });
  10670. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10671. get: function () {
  10672. return this._depthMask;
  10673. },
  10674. set: function (value) {
  10675. if (this._depthMask === value) {
  10676. return;
  10677. }
  10678. this._depthMask = value;
  10679. this._isDepthMaskDirty = true;
  10680. },
  10681. enumerable: true,
  10682. configurable: true
  10683. });
  10684. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10685. get: function () {
  10686. return this._depthTest;
  10687. },
  10688. set: function (value) {
  10689. if (this._depthTest === value) {
  10690. return;
  10691. }
  10692. this._depthTest = value;
  10693. this._isDepthTestDirty = true;
  10694. },
  10695. enumerable: true,
  10696. configurable: true
  10697. });
  10698. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10699. get: function () {
  10700. return this._frontFace;
  10701. },
  10702. set: function (value) {
  10703. if (this._frontFace === value) {
  10704. return;
  10705. }
  10706. this._frontFace = value;
  10707. this._isFrontFaceDirty = true;
  10708. },
  10709. enumerable: true,
  10710. configurable: true
  10711. });
  10712. _DepthCullingState.prototype.reset = function () {
  10713. this._depthMask = true;
  10714. this._depthTest = true;
  10715. this._depthFunc = null;
  10716. this._cullFace = null;
  10717. this._cull = null;
  10718. this._zOffset = 0;
  10719. this._frontFace = null;
  10720. this._isDepthTestDirty = true;
  10721. this._isDepthMaskDirty = true;
  10722. this._isDepthFuncDirty = false;
  10723. this._isCullFaceDirty = false;
  10724. this._isCullDirty = false;
  10725. this._isZOffsetDirty = false;
  10726. this._isFrontFaceDirty = false;
  10727. };
  10728. _DepthCullingState.prototype.apply = function (gl) {
  10729. if (!this.isDirty) {
  10730. return;
  10731. }
  10732. // Cull
  10733. if (this._isCullDirty) {
  10734. if (this.cull) {
  10735. gl.enable(gl.CULL_FACE);
  10736. }
  10737. else {
  10738. gl.disable(gl.CULL_FACE);
  10739. }
  10740. this._isCullDirty = false;
  10741. }
  10742. // Cull face
  10743. if (this._isCullFaceDirty) {
  10744. gl.cullFace(this.cullFace);
  10745. this._isCullFaceDirty = false;
  10746. }
  10747. // Depth mask
  10748. if (this._isDepthMaskDirty) {
  10749. gl.depthMask(this.depthMask);
  10750. this._isDepthMaskDirty = false;
  10751. }
  10752. // Depth test
  10753. if (this._isDepthTestDirty) {
  10754. if (this.depthTest) {
  10755. gl.enable(gl.DEPTH_TEST);
  10756. }
  10757. else {
  10758. gl.disable(gl.DEPTH_TEST);
  10759. }
  10760. this._isDepthTestDirty = false;
  10761. }
  10762. // Depth func
  10763. if (this._isDepthFuncDirty) {
  10764. gl.depthFunc(this.depthFunc);
  10765. this._isDepthFuncDirty = false;
  10766. }
  10767. // zOffset
  10768. if (this._isZOffsetDirty) {
  10769. if (this.zOffset) {
  10770. gl.enable(gl.POLYGON_OFFSET_FILL);
  10771. gl.polygonOffset(this.zOffset, 0);
  10772. }
  10773. else {
  10774. gl.disable(gl.POLYGON_OFFSET_FILL);
  10775. }
  10776. this._isZOffsetDirty = false;
  10777. }
  10778. // Front face
  10779. if (this._isFrontFaceDirty) {
  10780. gl.frontFace(this.frontFace);
  10781. this._isFrontFaceDirty = false;
  10782. }
  10783. };
  10784. return _DepthCullingState;
  10785. }());
  10786. BABYLON._DepthCullingState = _DepthCullingState;
  10787. })(BABYLON || (BABYLON = {}));
  10788. //# sourceMappingURL=babylon.depthCullingState.js.map
  10789. var BABYLON;
  10790. (function (BABYLON) {
  10791. /**
  10792. * @hidden
  10793. **/
  10794. var _StencilState = /** @class */ (function () {
  10795. function _StencilState() {
  10796. this._isStencilTestDirty = false;
  10797. this._isStencilMaskDirty = false;
  10798. this._isStencilFuncDirty = false;
  10799. this._isStencilOpDirty = false;
  10800. this.reset();
  10801. }
  10802. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10803. get: function () {
  10804. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10805. },
  10806. enumerable: true,
  10807. configurable: true
  10808. });
  10809. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10810. get: function () {
  10811. return this._stencilFunc;
  10812. },
  10813. set: function (value) {
  10814. if (this._stencilFunc === value) {
  10815. return;
  10816. }
  10817. this._stencilFunc = value;
  10818. this._isStencilFuncDirty = true;
  10819. },
  10820. enumerable: true,
  10821. configurable: true
  10822. });
  10823. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10824. get: function () {
  10825. return this._stencilFuncRef;
  10826. },
  10827. set: function (value) {
  10828. if (this._stencilFuncRef === value) {
  10829. return;
  10830. }
  10831. this._stencilFuncRef = value;
  10832. this._isStencilFuncDirty = true;
  10833. },
  10834. enumerable: true,
  10835. configurable: true
  10836. });
  10837. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10838. get: function () {
  10839. return this._stencilFuncMask;
  10840. },
  10841. set: function (value) {
  10842. if (this._stencilFuncMask === value) {
  10843. return;
  10844. }
  10845. this._stencilFuncMask = value;
  10846. this._isStencilFuncDirty = true;
  10847. },
  10848. enumerable: true,
  10849. configurable: true
  10850. });
  10851. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10852. get: function () {
  10853. return this._stencilOpStencilFail;
  10854. },
  10855. set: function (value) {
  10856. if (this._stencilOpStencilFail === value) {
  10857. return;
  10858. }
  10859. this._stencilOpStencilFail = value;
  10860. this._isStencilOpDirty = true;
  10861. },
  10862. enumerable: true,
  10863. configurable: true
  10864. });
  10865. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10866. get: function () {
  10867. return this._stencilOpDepthFail;
  10868. },
  10869. set: function (value) {
  10870. if (this._stencilOpDepthFail === value) {
  10871. return;
  10872. }
  10873. this._stencilOpDepthFail = value;
  10874. this._isStencilOpDirty = true;
  10875. },
  10876. enumerable: true,
  10877. configurable: true
  10878. });
  10879. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10880. get: function () {
  10881. return this._stencilOpStencilDepthPass;
  10882. },
  10883. set: function (value) {
  10884. if (this._stencilOpStencilDepthPass === value) {
  10885. return;
  10886. }
  10887. this._stencilOpStencilDepthPass = value;
  10888. this._isStencilOpDirty = true;
  10889. },
  10890. enumerable: true,
  10891. configurable: true
  10892. });
  10893. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10894. get: function () {
  10895. return this._stencilMask;
  10896. },
  10897. set: function (value) {
  10898. if (this._stencilMask === value) {
  10899. return;
  10900. }
  10901. this._stencilMask = value;
  10902. this._isStencilMaskDirty = true;
  10903. },
  10904. enumerable: true,
  10905. configurable: true
  10906. });
  10907. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10908. get: function () {
  10909. return this._stencilTest;
  10910. },
  10911. set: function (value) {
  10912. if (this._stencilTest === value) {
  10913. return;
  10914. }
  10915. this._stencilTest = value;
  10916. this._isStencilTestDirty = true;
  10917. },
  10918. enumerable: true,
  10919. configurable: true
  10920. });
  10921. _StencilState.prototype.reset = function () {
  10922. this._stencilTest = false;
  10923. this._stencilMask = 0xFF;
  10924. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10925. this._stencilFuncRef = 1;
  10926. this._stencilFuncMask = 0xFF;
  10927. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10928. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10929. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10930. this._isStencilTestDirty = true;
  10931. this._isStencilMaskDirty = true;
  10932. this._isStencilFuncDirty = true;
  10933. this._isStencilOpDirty = true;
  10934. };
  10935. _StencilState.prototype.apply = function (gl) {
  10936. if (!this.isDirty) {
  10937. return;
  10938. }
  10939. // Stencil test
  10940. if (this._isStencilTestDirty) {
  10941. if (this.stencilTest) {
  10942. gl.enable(gl.STENCIL_TEST);
  10943. }
  10944. else {
  10945. gl.disable(gl.STENCIL_TEST);
  10946. }
  10947. this._isStencilTestDirty = false;
  10948. }
  10949. // Stencil mask
  10950. if (this._isStencilMaskDirty) {
  10951. gl.stencilMask(this.stencilMask);
  10952. this._isStencilMaskDirty = false;
  10953. }
  10954. // Stencil func
  10955. if (this._isStencilFuncDirty) {
  10956. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10957. this._isStencilFuncDirty = false;
  10958. }
  10959. // Stencil op
  10960. if (this._isStencilOpDirty) {
  10961. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10962. this._isStencilOpDirty = false;
  10963. }
  10964. };
  10965. return _StencilState;
  10966. }());
  10967. BABYLON._StencilState = _StencilState;
  10968. })(BABYLON || (BABYLON = {}));
  10969. //# sourceMappingURL=babylon.stencilState.js.map
  10970. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10971. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10972. s = arguments[i];
  10973. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10974. t[p] = s[p];
  10975. }
  10976. return t;
  10977. };
  10978. var BABYLON;
  10979. (function (BABYLON) {
  10980. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10981. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10982. };
  10983. var compileRawShader = function (gl, source, type) {
  10984. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10985. gl.shaderSource(shader, source);
  10986. gl.compileShader(shader);
  10987. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10988. var log = gl.getShaderInfoLog(shader);
  10989. if (log) {
  10990. throw new Error(log);
  10991. }
  10992. }
  10993. if (!shader) {
  10994. throw new Error("Something went wrong while compile the shader.");
  10995. }
  10996. return shader;
  10997. };
  10998. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10999. var magFilter = gl.NEAREST;
  11000. var minFilter = gl.NEAREST;
  11001. switch (samplingMode) {
  11002. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11003. magFilter = gl.LINEAR;
  11004. if (generateMipMaps) {
  11005. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11006. }
  11007. else {
  11008. minFilter = gl.LINEAR;
  11009. }
  11010. break;
  11011. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11012. magFilter = gl.LINEAR;
  11013. if (generateMipMaps) {
  11014. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11015. }
  11016. else {
  11017. minFilter = gl.LINEAR;
  11018. }
  11019. break;
  11020. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11021. magFilter = gl.NEAREST;
  11022. if (generateMipMaps) {
  11023. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11024. }
  11025. else {
  11026. minFilter = gl.NEAREST;
  11027. }
  11028. break;
  11029. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11030. magFilter = gl.NEAREST;
  11031. if (generateMipMaps) {
  11032. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11033. }
  11034. else {
  11035. minFilter = gl.NEAREST;
  11036. }
  11037. break;
  11038. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11039. magFilter = gl.NEAREST;
  11040. if (generateMipMaps) {
  11041. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11042. }
  11043. else {
  11044. minFilter = gl.LINEAR;
  11045. }
  11046. break;
  11047. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11048. magFilter = gl.NEAREST;
  11049. if (generateMipMaps) {
  11050. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11051. }
  11052. else {
  11053. minFilter = gl.LINEAR;
  11054. }
  11055. break;
  11056. case BABYLON.Texture.NEAREST_LINEAR:
  11057. magFilter = gl.NEAREST;
  11058. minFilter = gl.LINEAR;
  11059. break;
  11060. case BABYLON.Texture.NEAREST_NEAREST:
  11061. magFilter = gl.NEAREST;
  11062. minFilter = gl.NEAREST;
  11063. break;
  11064. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11065. magFilter = gl.LINEAR;
  11066. if (generateMipMaps) {
  11067. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11068. }
  11069. else {
  11070. minFilter = gl.NEAREST;
  11071. }
  11072. break;
  11073. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11074. magFilter = gl.LINEAR;
  11075. if (generateMipMaps) {
  11076. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11077. }
  11078. else {
  11079. minFilter = gl.NEAREST;
  11080. }
  11081. break;
  11082. case BABYLON.Texture.LINEAR_LINEAR:
  11083. magFilter = gl.LINEAR;
  11084. minFilter = gl.LINEAR;
  11085. break;
  11086. case BABYLON.Texture.LINEAR_NEAREST:
  11087. magFilter = gl.LINEAR;
  11088. minFilter = gl.NEAREST;
  11089. break;
  11090. }
  11091. return {
  11092. min: minFilter,
  11093. mag: magFilter
  11094. };
  11095. };
  11096. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11097. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11098. var img;
  11099. var onload = function () {
  11100. loadedImages[index] = img;
  11101. loadedImages._internalCount++;
  11102. if (scene) {
  11103. scene._removePendingData(img);
  11104. }
  11105. if (loadedImages._internalCount === 6) {
  11106. onfinish(loadedImages);
  11107. }
  11108. };
  11109. var onerror = function (message, exception) {
  11110. if (scene) {
  11111. scene._removePendingData(img);
  11112. }
  11113. if (onErrorCallBack) {
  11114. onErrorCallBack(message, exception);
  11115. }
  11116. };
  11117. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11118. if (scene) {
  11119. scene._addPendingData(img);
  11120. }
  11121. };
  11122. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11123. if (onError === void 0) { onError = null; }
  11124. var loadedImages = [];
  11125. loadedImages._internalCount = 0;
  11126. for (var index = 0; index < 6; index++) {
  11127. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11128. }
  11129. };
  11130. var BufferPointer = /** @class */ (function () {
  11131. function BufferPointer() {
  11132. }
  11133. return BufferPointer;
  11134. }());
  11135. /**
  11136. * Interface for attribute information associated with buffer instanciation
  11137. */
  11138. var InstancingAttributeInfo = /** @class */ (function () {
  11139. function InstancingAttributeInfo() {
  11140. }
  11141. return InstancingAttributeInfo;
  11142. }());
  11143. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11144. /**
  11145. * Define options used to create a render target texture
  11146. */
  11147. var RenderTargetCreationOptions = /** @class */ (function () {
  11148. function RenderTargetCreationOptions() {
  11149. }
  11150. return RenderTargetCreationOptions;
  11151. }());
  11152. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11153. /**
  11154. * Define options used to create a depth texture
  11155. */
  11156. var DepthTextureCreationOptions = /** @class */ (function () {
  11157. function DepthTextureCreationOptions() {
  11158. }
  11159. return DepthTextureCreationOptions;
  11160. }());
  11161. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11162. /**
  11163. * Class used to describe the capabilities of the engine relatively to the current browser
  11164. */
  11165. var EngineCapabilities = /** @class */ (function () {
  11166. function EngineCapabilities() {
  11167. }
  11168. return EngineCapabilities;
  11169. }());
  11170. BABYLON.EngineCapabilities = EngineCapabilities;
  11171. /**
  11172. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11173. */
  11174. var Engine = /** @class */ (function () {
  11175. /**
  11176. * Creates a new engine
  11177. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11178. * @param antialias defines enable antialiasing (default: false)
  11179. * @param options defines further options to be sent to the getContext() function
  11180. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11181. */
  11182. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11183. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11184. var _this = this;
  11185. // Public members
  11186. /**
  11187. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11188. */
  11189. this.forcePOTTextures = false;
  11190. /**
  11191. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11192. */
  11193. this.isFullscreen = false;
  11194. /**
  11195. * Gets a boolean indicating if the pointer is currently locked
  11196. */
  11197. this.isPointerLock = false;
  11198. /**
  11199. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11200. */
  11201. this.cullBackFaces = true;
  11202. /**
  11203. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11204. */
  11205. this.renderEvenInBackground = true;
  11206. /**
  11207. * Gets or sets a boolean indicating that cache can be kept between frames
  11208. */
  11209. this.preventCacheWipeBetweenFrames = false;
  11210. /**
  11211. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11212. **/
  11213. this.enableOfflineSupport = false;
  11214. /**
  11215. * 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)
  11216. **/
  11217. this.disableManifestCheck = false;
  11218. /**
  11219. * Gets the list of created scenes
  11220. */
  11221. this.scenes = new Array();
  11222. /**
  11223. * Gets the list of created postprocesses
  11224. */
  11225. this.postProcesses = new Array();
  11226. // Observables
  11227. /**
  11228. * Observable event triggered each time the rendering canvas is resized
  11229. */
  11230. this.onResizeObservable = new BABYLON.Observable();
  11231. /**
  11232. * Observable event triggered each time the canvas loses focus
  11233. */
  11234. this.onCanvasBlurObservable = new BABYLON.Observable();
  11235. /**
  11236. * Observable event triggered each time the canvas gains focus
  11237. */
  11238. this.onCanvasFocusObservable = new BABYLON.Observable();
  11239. /**
  11240. * Observable event triggered each time the canvas receives pointerout event
  11241. */
  11242. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11243. /**
  11244. * Observable event triggered before each texture is initialized
  11245. */
  11246. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11247. //WebVR
  11248. this._vrDisplay = undefined;
  11249. this._vrSupported = false;
  11250. this._vrExclusivePointerMode = false;
  11251. // Uniform buffers list
  11252. /**
  11253. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11254. */
  11255. this.disableUniformBuffers = false;
  11256. /** @hidden */
  11257. this._uniformBuffers = new Array();
  11258. // Observables
  11259. /**
  11260. * Observable raised when the engine begins a new frame
  11261. */
  11262. this.onBeginFrameObservable = new BABYLON.Observable();
  11263. /**
  11264. * Observable raised when the engine ends the current frame
  11265. */
  11266. this.onEndFrameObservable = new BABYLON.Observable();
  11267. /**
  11268. * Observable raised when the engine is about to compile a shader
  11269. */
  11270. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11271. /**
  11272. * Observable raised when the engine has jsut compiled a shader
  11273. */
  11274. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11275. this._windowIsBackground = false;
  11276. this._webGLVersion = 1.0;
  11277. /** @hidden */
  11278. this._badOS = false;
  11279. /** @hidden */
  11280. this._badDesktopOS = false;
  11281. /**
  11282. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11283. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11284. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11285. */
  11286. this.disableTextureBindingOptimization = false;
  11287. /**
  11288. * Observable signaled when VR display mode changes
  11289. */
  11290. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11291. /**
  11292. * Observable signaled when VR request present is complete
  11293. */
  11294. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11295. /**
  11296. * Observable signaled when VR request present starts
  11297. */
  11298. this.onVRRequestPresentStart = new BABYLON.Observable();
  11299. this._colorWrite = true;
  11300. /** @hidden */
  11301. this._drawCalls = new BABYLON.PerfCounter();
  11302. /** @hidden */
  11303. this._textureCollisions = new BABYLON.PerfCounter();
  11304. this._renderingQueueLaunched = false;
  11305. this._activeRenderLoops = new Array();
  11306. // Deterministic lockstepMaxSteps
  11307. this._deterministicLockstep = false;
  11308. this._lockstepMaxSteps = 4;
  11309. // Lost context
  11310. /**
  11311. * Observable signaled when a context lost event is raised
  11312. */
  11313. this.onContextLostObservable = new BABYLON.Observable();
  11314. /**
  11315. * Observable signaled when a context restored event is raised
  11316. */
  11317. this.onContextRestoredObservable = new BABYLON.Observable();
  11318. this._contextWasLost = false;
  11319. this._doNotHandleContextLost = false;
  11320. // FPS
  11321. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11322. this._fps = 60;
  11323. this._deltaTime = 0;
  11324. /**
  11325. * Turn this value on if you want to pause FPS computation when in background
  11326. */
  11327. this.disablePerformanceMonitorInBackground = false;
  11328. // States
  11329. /** @hidden */
  11330. this._depthCullingState = new BABYLON._DepthCullingState();
  11331. /** @hidden */
  11332. this._stencilState = new BABYLON._StencilState();
  11333. /** @hidden */
  11334. this._alphaState = new BABYLON._AlphaState();
  11335. /** @hidden */
  11336. this._alphaMode = Engine.ALPHA_DISABLE;
  11337. // Cache
  11338. this._internalTexturesCache = new Array();
  11339. /** @hidden */
  11340. this._activeChannel = 0;
  11341. this._currentTextureChannel = -1;
  11342. /** @hidden */
  11343. this._boundTexturesCache = {};
  11344. this._compiledEffects = {};
  11345. this._vertexAttribArraysEnabled = [];
  11346. this._uintIndicesCurrentlySet = false;
  11347. this._currentBoundBuffer = new Array();
  11348. this._currentBufferPointers = new Array();
  11349. this._currentInstanceLocations = new Array();
  11350. this._currentInstanceBuffers = new Array();
  11351. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11352. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11353. this._vaoRecordInProgress = false;
  11354. this._mustWipeVertexAttributes = false;
  11355. this._nextFreeTextureSlots = new Array();
  11356. this._maxSimultaneousTextures = 0;
  11357. this._activeRequests = new Array();
  11358. // Hardware supported Compressed Textures
  11359. this._texturesSupported = new Array();
  11360. /**
  11361. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11362. */
  11363. this.premultipliedAlpha = true;
  11364. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11365. this._onVRFullScreenTriggered = function () {
  11366. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11367. //get the old size before we change
  11368. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11369. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11370. //get the width and height, change the render size
  11371. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11372. _this.setHardwareScalingLevel(1);
  11373. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11374. }
  11375. else {
  11376. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11377. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11378. }
  11379. };
  11380. this._unpackFlipYCached = null;
  11381. this._boundUniforms = {};
  11382. // Register promises
  11383. BABYLON.PromisePolyfill.Apply();
  11384. var canvas = null;
  11385. Engine.Instances.push(this);
  11386. if (!canvasOrContext) {
  11387. return;
  11388. }
  11389. options = options || {};
  11390. if (canvasOrContext.getContext) {
  11391. canvas = canvasOrContext;
  11392. this._renderingCanvas = canvas;
  11393. if (antialias != null) {
  11394. options.antialias = antialias;
  11395. }
  11396. if (options.deterministicLockstep === undefined) {
  11397. options.deterministicLockstep = false;
  11398. }
  11399. if (options.lockstepMaxSteps === undefined) {
  11400. options.lockstepMaxSteps = 4;
  11401. }
  11402. if (options.preserveDrawingBuffer === undefined) {
  11403. options.preserveDrawingBuffer = false;
  11404. }
  11405. if (options.audioEngine === undefined) {
  11406. options.audioEngine = true;
  11407. }
  11408. if (options.stencil === undefined) {
  11409. options.stencil = true;
  11410. }
  11411. if (options.premultipliedAlpha === false) {
  11412. this.premultipliedAlpha = false;
  11413. }
  11414. this._deterministicLockstep = options.deterministicLockstep;
  11415. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11416. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11417. // Exceptions
  11418. if (navigator && navigator.userAgent) {
  11419. var ua = navigator.userAgent;
  11420. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11421. var exception = _a[_i];
  11422. var key = exception.key;
  11423. var targets = exception.targets;
  11424. if (ua.indexOf(key) > -1) {
  11425. if (exception.capture && exception.captureConstraint) {
  11426. var capture = exception.capture;
  11427. var constraint = exception.captureConstraint;
  11428. var regex = new RegExp(capture);
  11429. var matches = regex.exec(ua);
  11430. if (matches && matches.length > 0) {
  11431. var capturedValue = parseInt(matches[matches.length - 1]);
  11432. if (capturedValue >= constraint) {
  11433. continue;
  11434. }
  11435. }
  11436. }
  11437. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11438. var target = targets_1[_b];
  11439. switch (target) {
  11440. case "uniformBuffer":
  11441. this.disableUniformBuffers = true;
  11442. break;
  11443. case "textureBindingOptimization":
  11444. this.disableTextureBindingOptimization = true;
  11445. break;
  11446. }
  11447. }
  11448. }
  11449. }
  11450. }
  11451. // GL
  11452. if (!options.disableWebGL2Support) {
  11453. try {
  11454. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11455. if (this._gl) {
  11456. this._webGLVersion = 2.0;
  11457. }
  11458. }
  11459. catch (e) {
  11460. // Do nothing
  11461. }
  11462. }
  11463. if (!this._gl) {
  11464. if (!canvas) {
  11465. throw new Error("The provided canvas is null or undefined.");
  11466. }
  11467. try {
  11468. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11469. }
  11470. catch (e) {
  11471. throw new Error("WebGL not supported");
  11472. }
  11473. }
  11474. if (!this._gl) {
  11475. throw new Error("WebGL not supported");
  11476. }
  11477. this._onCanvasFocus = function () {
  11478. _this.onCanvasFocusObservable.notifyObservers(_this);
  11479. };
  11480. this._onCanvasBlur = function () {
  11481. _this.onCanvasBlurObservable.notifyObservers(_this);
  11482. };
  11483. canvas.addEventListener("focus", this._onCanvasFocus);
  11484. canvas.addEventListener("blur", this._onCanvasBlur);
  11485. this._onBlur = function () {
  11486. if (_this.disablePerformanceMonitorInBackground) {
  11487. _this._performanceMonitor.disable();
  11488. }
  11489. _this._windowIsBackground = true;
  11490. };
  11491. this._onFocus = function () {
  11492. if (_this.disablePerformanceMonitorInBackground) {
  11493. _this._performanceMonitor.enable();
  11494. }
  11495. _this._windowIsBackground = false;
  11496. };
  11497. this._onCanvasPointerOut = function (ev) {
  11498. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11499. };
  11500. window.addEventListener("blur", this._onBlur);
  11501. window.addEventListener("focus", this._onFocus);
  11502. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11503. // Context lost
  11504. if (!this._doNotHandleContextLost) {
  11505. this._onContextLost = function (evt) {
  11506. evt.preventDefault();
  11507. _this._contextWasLost = true;
  11508. BABYLON.Tools.Warn("WebGL context lost.");
  11509. _this.onContextLostObservable.notifyObservers(_this);
  11510. };
  11511. this._onContextRestored = function (evt) {
  11512. // Adding a timeout to avoid race condition at browser level
  11513. setTimeout(function () {
  11514. // Rebuild gl context
  11515. _this._initGLContext();
  11516. // Rebuild effects
  11517. _this._rebuildEffects();
  11518. // Rebuild textures
  11519. _this._rebuildInternalTextures();
  11520. // Rebuild buffers
  11521. _this._rebuildBuffers();
  11522. // Cache
  11523. _this.wipeCaches(true);
  11524. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11525. _this.onContextRestoredObservable.notifyObservers(_this);
  11526. _this._contextWasLost = false;
  11527. }, 0);
  11528. };
  11529. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11530. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11531. }
  11532. }
  11533. else {
  11534. this._gl = canvasOrContext;
  11535. this._renderingCanvas = this._gl.canvas;
  11536. if (this._gl.renderbufferStorageMultisample) {
  11537. this._webGLVersion = 2.0;
  11538. }
  11539. options.stencil = this._gl.getContextAttributes().stencil;
  11540. }
  11541. // Viewport
  11542. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11543. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11544. this.resize();
  11545. this._isStencilEnable = options.stencil ? true : false;
  11546. this._initGLContext();
  11547. if (canvas) {
  11548. // Fullscreen
  11549. this._onFullscreenChange = function () {
  11550. if (document.fullscreen !== undefined) {
  11551. _this.isFullscreen = document.fullscreen;
  11552. }
  11553. else if (document.mozFullScreen !== undefined) {
  11554. _this.isFullscreen = document.mozFullScreen;
  11555. }
  11556. else if (document.webkitIsFullScreen !== undefined) {
  11557. _this.isFullscreen = document.webkitIsFullScreen;
  11558. }
  11559. else if (document.msIsFullScreen !== undefined) {
  11560. _this.isFullscreen = document.msIsFullScreen;
  11561. }
  11562. // Pointer lock
  11563. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11564. canvas.requestPointerLock = canvas.requestPointerLock ||
  11565. canvas.msRequestPointerLock ||
  11566. canvas.mozRequestPointerLock ||
  11567. canvas.webkitRequestPointerLock;
  11568. if (canvas.requestPointerLock) {
  11569. canvas.requestPointerLock();
  11570. }
  11571. }
  11572. };
  11573. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11574. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11575. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11576. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11577. // Pointer lock
  11578. this._onPointerLockChange = function () {
  11579. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11580. document.webkitPointerLockElement === canvas ||
  11581. document.msPointerLockElement === canvas ||
  11582. document.pointerLockElement === canvas);
  11583. };
  11584. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11585. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11586. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11587. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11588. this._onVRDisplayPointerRestricted = function () {
  11589. if (canvas) {
  11590. canvas.requestPointerLock();
  11591. }
  11592. };
  11593. this._onVRDisplayPointerUnrestricted = function () {
  11594. document.exitPointerLock();
  11595. };
  11596. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11597. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11598. }
  11599. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11600. Engine.audioEngine = new BABYLON.AudioEngine();
  11601. }
  11602. // Prepare buffer pointers
  11603. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11604. this._currentBufferPointers[i] = new BufferPointer();
  11605. }
  11606. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11607. // Load WebVR Devices
  11608. if (options.autoEnableWebVR) {
  11609. this.initWebVR();
  11610. }
  11611. // Detect if we are running on a faulty buggy OS.
  11612. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11613. // Detect if we are running on a faulty buggy desktop OS.
  11614. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11615. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11616. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11617. }
  11618. Object.defineProperty(Engine, "LastCreatedEngine", {
  11619. /**
  11620. * Gets the latest created engine
  11621. */
  11622. get: function () {
  11623. if (Engine.Instances.length === 0) {
  11624. return null;
  11625. }
  11626. return Engine.Instances[Engine.Instances.length - 1];
  11627. },
  11628. enumerable: true,
  11629. configurable: true
  11630. });
  11631. Object.defineProperty(Engine, "LastCreatedScene", {
  11632. /**
  11633. * Gets the latest created scene
  11634. */
  11635. get: function () {
  11636. var lastCreatedEngine = Engine.LastCreatedEngine;
  11637. if (!lastCreatedEngine) {
  11638. return null;
  11639. }
  11640. if (lastCreatedEngine.scenes.length === 0) {
  11641. return null;
  11642. }
  11643. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11644. },
  11645. enumerable: true,
  11646. configurable: true
  11647. });
  11648. /**
  11649. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11650. * @param flag defines which part of the materials must be marked as dirty
  11651. * @param predicate defines a predicate used to filter which materials should be affected
  11652. */
  11653. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11654. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11655. var engine = Engine.Instances[engineIndex];
  11656. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11657. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11658. }
  11659. }
  11660. };
  11661. Object.defineProperty(Engine, "NEVER", {
  11662. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11663. get: function () {
  11664. return Engine._NEVER;
  11665. },
  11666. enumerable: true,
  11667. configurable: true
  11668. });
  11669. Object.defineProperty(Engine, "ALWAYS", {
  11670. /** 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 */
  11671. get: function () {
  11672. return Engine._ALWAYS;
  11673. },
  11674. enumerable: true,
  11675. configurable: true
  11676. });
  11677. Object.defineProperty(Engine, "LESS", {
  11678. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11679. get: function () {
  11680. return Engine._LESS;
  11681. },
  11682. enumerable: true,
  11683. configurable: true
  11684. });
  11685. Object.defineProperty(Engine, "EQUAL", {
  11686. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11687. get: function () {
  11688. return Engine._EQUAL;
  11689. },
  11690. enumerable: true,
  11691. configurable: true
  11692. });
  11693. Object.defineProperty(Engine, "LEQUAL", {
  11694. /** 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 */
  11695. get: function () {
  11696. return Engine._LEQUAL;
  11697. },
  11698. enumerable: true,
  11699. configurable: true
  11700. });
  11701. Object.defineProperty(Engine, "GREATER", {
  11702. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11703. get: function () {
  11704. return Engine._GREATER;
  11705. },
  11706. enumerable: true,
  11707. configurable: true
  11708. });
  11709. Object.defineProperty(Engine, "GEQUAL", {
  11710. /** 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 */
  11711. get: function () {
  11712. return Engine._GEQUAL;
  11713. },
  11714. enumerable: true,
  11715. configurable: true
  11716. });
  11717. Object.defineProperty(Engine, "NOTEQUAL", {
  11718. /** 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 */
  11719. get: function () {
  11720. return Engine._NOTEQUAL;
  11721. },
  11722. enumerable: true,
  11723. configurable: true
  11724. });
  11725. Object.defineProperty(Engine, "KEEP", {
  11726. /** Passed to stencilOperation to specify that stencil value must be kept */
  11727. get: function () {
  11728. return Engine._KEEP;
  11729. },
  11730. enumerable: true,
  11731. configurable: true
  11732. });
  11733. Object.defineProperty(Engine, "REPLACE", {
  11734. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11735. get: function () {
  11736. return Engine._REPLACE;
  11737. },
  11738. enumerable: true,
  11739. configurable: true
  11740. });
  11741. Object.defineProperty(Engine, "INCR", {
  11742. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11743. get: function () {
  11744. return Engine._INCR;
  11745. },
  11746. enumerable: true,
  11747. configurable: true
  11748. });
  11749. Object.defineProperty(Engine, "DECR", {
  11750. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11751. get: function () {
  11752. return Engine._DECR;
  11753. },
  11754. enumerable: true,
  11755. configurable: true
  11756. });
  11757. Object.defineProperty(Engine, "INVERT", {
  11758. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11759. get: function () {
  11760. return Engine._INVERT;
  11761. },
  11762. enumerable: true,
  11763. configurable: true
  11764. });
  11765. Object.defineProperty(Engine, "INCR_WRAP", {
  11766. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11767. get: function () {
  11768. return Engine._INCR_WRAP;
  11769. },
  11770. enumerable: true,
  11771. configurable: true
  11772. });
  11773. Object.defineProperty(Engine, "DECR_WRAP", {
  11774. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11775. get: function () {
  11776. return Engine._DECR_WRAP;
  11777. },
  11778. enumerable: true,
  11779. configurable: true
  11780. });
  11781. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11782. // Alpha
  11783. /** Defines that alpha blending is disabled */
  11784. get: function () {
  11785. return Engine._ALPHA_DISABLE;
  11786. },
  11787. enumerable: true,
  11788. configurable: true
  11789. });
  11790. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11791. /** Defines that alpha blending to SRC + DEST */
  11792. get: function () {
  11793. return Engine._ALPHA_ONEONE;
  11794. },
  11795. enumerable: true,
  11796. configurable: true
  11797. });
  11798. Object.defineProperty(Engine, "ALPHA_ADD", {
  11799. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11800. get: function () {
  11801. return Engine._ALPHA_ADD;
  11802. },
  11803. enumerable: true,
  11804. configurable: true
  11805. });
  11806. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11807. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11808. get: function () {
  11809. return Engine._ALPHA_COMBINE;
  11810. },
  11811. enumerable: true,
  11812. configurable: true
  11813. });
  11814. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11815. /** Defines that alpha blending to DEST - SRC * DEST */
  11816. get: function () {
  11817. return Engine._ALPHA_SUBTRACT;
  11818. },
  11819. enumerable: true,
  11820. configurable: true
  11821. });
  11822. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11823. /** Defines that alpha blending to SRC * DEST */
  11824. get: function () {
  11825. return Engine._ALPHA_MULTIPLY;
  11826. },
  11827. enumerable: true,
  11828. configurable: true
  11829. });
  11830. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11831. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11832. get: function () {
  11833. return Engine._ALPHA_MAXIMIZED;
  11834. },
  11835. enumerable: true,
  11836. configurable: true
  11837. });
  11838. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11839. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11840. get: function () {
  11841. return Engine._ALPHA_PREMULTIPLIED;
  11842. },
  11843. enumerable: true,
  11844. configurable: true
  11845. });
  11846. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11847. /**
  11848. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11849. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11850. */
  11851. get: function () {
  11852. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11853. },
  11854. enumerable: true,
  11855. configurable: true
  11856. });
  11857. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11858. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11859. get: function () {
  11860. return Engine._ALPHA_INTERPOLATE;
  11861. },
  11862. enumerable: true,
  11863. configurable: true
  11864. });
  11865. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11866. /**
  11867. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11868. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11869. */
  11870. get: function () {
  11871. return Engine._ALPHA_SCREENMODE;
  11872. },
  11873. enumerable: true,
  11874. configurable: true
  11875. });
  11876. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11877. // Delays
  11878. /** Defines that the ressource is not delayed*/
  11879. get: function () {
  11880. return Engine._DELAYLOADSTATE_NONE;
  11881. },
  11882. enumerable: true,
  11883. configurable: true
  11884. });
  11885. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11886. /** Defines that the ressource was successfully delay loaded */
  11887. get: function () {
  11888. return Engine._DELAYLOADSTATE_LOADED;
  11889. },
  11890. enumerable: true,
  11891. configurable: true
  11892. });
  11893. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11894. /** Defines that the ressource is currently delay loading */
  11895. get: function () {
  11896. return Engine._DELAYLOADSTATE_LOADING;
  11897. },
  11898. enumerable: true,
  11899. configurable: true
  11900. });
  11901. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11902. /** Defines that the ressource is delayed and has not started loading */
  11903. get: function () {
  11904. return Engine._DELAYLOADSTATE_NOTLOADED;
  11905. },
  11906. enumerable: true,
  11907. configurable: true
  11908. });
  11909. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11910. /** ALPHA */
  11911. get: function () {
  11912. return Engine._TEXTUREFORMAT_ALPHA;
  11913. },
  11914. enumerable: true,
  11915. configurable: true
  11916. });
  11917. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11918. /** LUMINANCE */
  11919. get: function () {
  11920. return Engine._TEXTUREFORMAT_LUMINANCE;
  11921. },
  11922. enumerable: true,
  11923. configurable: true
  11924. });
  11925. Object.defineProperty(Engine, "TEXTUREFORMAT_R", {
  11926. /**
  11927. * R
  11928. */
  11929. get: function () {
  11930. return Engine._TEXTUREFORMAT_R;
  11931. },
  11932. enumerable: true,
  11933. configurable: true
  11934. });
  11935. Object.defineProperty(Engine, "TEXTUREFORMAT_RG", {
  11936. /**
  11937. * RG
  11938. */
  11939. get: function () {
  11940. return Engine._TEXTUREFORMAT_RG;
  11941. },
  11942. enumerable: true,
  11943. configurable: true
  11944. });
  11945. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11946. /** LUMINANCE_ALPHA */
  11947. get: function () {
  11948. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11949. },
  11950. enumerable: true,
  11951. configurable: true
  11952. });
  11953. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11954. /** RGB */
  11955. get: function () {
  11956. return Engine._TEXTUREFORMAT_RGB;
  11957. },
  11958. enumerable: true,
  11959. configurable: true
  11960. });
  11961. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11962. /** RGBA */
  11963. get: function () {
  11964. return Engine._TEXTUREFORMAT_RGBA;
  11965. },
  11966. enumerable: true,
  11967. configurable: true
  11968. });
  11969. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11970. /** UNSIGNED_INT */
  11971. get: function () {
  11972. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11973. },
  11974. enumerable: true,
  11975. configurable: true
  11976. });
  11977. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11978. /** FLOAT */
  11979. get: function () {
  11980. return Engine._TEXTURETYPE_FLOAT;
  11981. },
  11982. enumerable: true,
  11983. configurable: true
  11984. });
  11985. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11986. /** HALF_FLOAT */
  11987. get: function () {
  11988. return Engine._TEXTURETYPE_HALF_FLOAT;
  11989. },
  11990. enumerable: true,
  11991. configurable: true
  11992. });
  11993. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11994. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  11995. get: function () {
  11996. return Engine._SCALEMODE_FLOOR;
  11997. },
  11998. enumerable: true,
  11999. configurable: true
  12000. });
  12001. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12002. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12003. get: function () {
  12004. return Engine._SCALEMODE_NEAREST;
  12005. },
  12006. enumerable: true,
  12007. configurable: true
  12008. });
  12009. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12010. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12011. get: function () {
  12012. return Engine._SCALEMODE_CEILING;
  12013. },
  12014. enumerable: true,
  12015. configurable: true
  12016. });
  12017. Object.defineProperty(Engine, "Version", {
  12018. /**
  12019. * Returns the current version of the framework
  12020. */
  12021. get: function () {
  12022. return "3.3.0-alpha.8";
  12023. },
  12024. enumerable: true,
  12025. configurable: true
  12026. });
  12027. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12028. /**
  12029. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12030. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12031. */
  12032. get: function () {
  12033. return this._vrExclusivePointerMode;
  12034. },
  12035. enumerable: true,
  12036. configurable: true
  12037. });
  12038. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12039. /**
  12040. * Gets a boolean indicating that the engine supports uniform buffers
  12041. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12042. */
  12043. get: function () {
  12044. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12045. },
  12046. enumerable: true,
  12047. configurable: true
  12048. });
  12049. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12050. /**
  12051. * Gets a boolean indicating that only power of 2 textures are supported
  12052. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12053. */
  12054. get: function () {
  12055. return this._webGLVersion < 2 || this.forcePOTTextures;
  12056. },
  12057. enumerable: true,
  12058. configurable: true
  12059. });
  12060. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12061. /**
  12062. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12063. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12064. */
  12065. get: function () {
  12066. return this._doNotHandleContextLost;
  12067. },
  12068. set: function (value) {
  12069. this._doNotHandleContextLost = value;
  12070. },
  12071. enumerable: true,
  12072. configurable: true
  12073. });
  12074. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12075. /**
  12076. * Gets the performance monitor attached to this engine
  12077. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12078. */
  12079. get: function () {
  12080. return this._performanceMonitor;
  12081. },
  12082. enumerable: true,
  12083. configurable: true
  12084. });
  12085. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12086. /**
  12087. * Gets the list of texture formats supported
  12088. */
  12089. get: function () {
  12090. return this._texturesSupported;
  12091. },
  12092. enumerable: true,
  12093. configurable: true
  12094. });
  12095. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12096. /**
  12097. * Gets the list of texture formats in use
  12098. */
  12099. get: function () {
  12100. return this._textureFormatInUse;
  12101. },
  12102. enumerable: true,
  12103. configurable: true
  12104. });
  12105. Object.defineProperty(Engine.prototype, "currentViewport", {
  12106. /**
  12107. * Gets the current viewport
  12108. */
  12109. get: function () {
  12110. return this._cachedViewport;
  12111. },
  12112. enumerable: true,
  12113. configurable: true
  12114. });
  12115. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12116. /**
  12117. * Gets the default empty texture
  12118. */
  12119. get: function () {
  12120. if (!this._emptyTexture) {
  12121. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12122. }
  12123. return this._emptyTexture;
  12124. },
  12125. enumerable: true,
  12126. configurable: true
  12127. });
  12128. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12129. /**
  12130. * Gets the default empty 3D texture
  12131. */
  12132. get: function () {
  12133. if (!this._emptyTexture3D) {
  12134. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12135. }
  12136. return this._emptyTexture3D;
  12137. },
  12138. enumerable: true,
  12139. configurable: true
  12140. });
  12141. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12142. /**
  12143. * Gets the default empty cube texture
  12144. */
  12145. get: function () {
  12146. if (!this._emptyCubeTexture) {
  12147. var faceData = new Uint8Array(4);
  12148. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12149. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12150. }
  12151. return this._emptyCubeTexture;
  12152. },
  12153. enumerable: true,
  12154. configurable: true
  12155. });
  12156. Engine.prototype._rebuildInternalTextures = function () {
  12157. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12158. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12159. var internalTexture = currentState_1[_i];
  12160. internalTexture._rebuild();
  12161. }
  12162. };
  12163. Engine.prototype._rebuildEffects = function () {
  12164. for (var key in this._compiledEffects) {
  12165. var effect = this._compiledEffects[key];
  12166. effect._prepareEffect();
  12167. }
  12168. BABYLON.Effect.ResetCache();
  12169. };
  12170. Engine.prototype._rebuildBuffers = function () {
  12171. // Index / Vertex
  12172. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12173. var scene = _a[_i];
  12174. scene.resetCachedMaterial();
  12175. scene._rebuildGeometries();
  12176. scene._rebuildTextures();
  12177. }
  12178. // Uniforms
  12179. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12180. var uniformBuffer = _c[_b];
  12181. uniformBuffer._rebuild();
  12182. }
  12183. };
  12184. Engine.prototype._initGLContext = function () {
  12185. // Caps
  12186. this._caps = new EngineCapabilities();
  12187. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12188. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12189. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12190. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12191. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12192. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12193. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12194. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12195. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12196. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12197. // Infos
  12198. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12199. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12200. if (rendererInfo != null) {
  12201. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12202. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12203. }
  12204. if (!this._glVendor) {
  12205. this._glVendor = "Unknown vendor";
  12206. }
  12207. if (!this._glRenderer) {
  12208. this._glRenderer = "Unknown renderer";
  12209. }
  12210. // Constants
  12211. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12212. if (this._gl.RGBA16F !== 0x881A) {
  12213. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12214. }
  12215. if (this._gl.RGBA32F !== 0x8814) {
  12216. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12217. }
  12218. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12219. this._gl.DEPTH24_STENCIL8 = 35056;
  12220. }
  12221. // Extensions
  12222. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12223. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12224. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12225. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12226. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12227. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12228. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12229. 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');
  12230. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12231. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12232. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12233. this._caps.highPrecisionShaderSupported = true;
  12234. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12235. if (this._caps.timerQuery) {
  12236. if (this._webGLVersion === 1) {
  12237. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12238. }
  12239. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12240. }
  12241. // Checks if some of the format renders first to allow the use of webgl inspector.
  12242. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12243. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12244. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12245. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12246. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12247. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12248. if (this._webGLVersion > 1) {
  12249. this._gl.HALF_FLOAT_OES = 0x140B;
  12250. }
  12251. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12252. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12253. // Draw buffers
  12254. if (this._webGLVersion > 1) {
  12255. this._caps.drawBuffersExtension = true;
  12256. }
  12257. else {
  12258. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12259. if (drawBuffersExtension !== null) {
  12260. this._caps.drawBuffersExtension = true;
  12261. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12262. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12263. for (var i = 0; i < 16; i++) {
  12264. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12265. }
  12266. }
  12267. else {
  12268. this._caps.drawBuffersExtension = false;
  12269. }
  12270. }
  12271. // Depth Texture
  12272. if (this._webGLVersion > 1) {
  12273. this._caps.depthTextureExtension = true;
  12274. }
  12275. else {
  12276. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12277. if (depthTextureExtension != null) {
  12278. this._caps.depthTextureExtension = true;
  12279. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12280. }
  12281. }
  12282. // Vertex array object
  12283. if (this._webGLVersion > 1) {
  12284. this._caps.vertexArrayObject = true;
  12285. }
  12286. else {
  12287. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12288. if (vertexArrayObjectExtension != null) {
  12289. this._caps.vertexArrayObject = true;
  12290. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12291. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12292. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12293. }
  12294. else {
  12295. this._caps.vertexArrayObject = false;
  12296. }
  12297. }
  12298. // Instances count
  12299. if (this._webGLVersion > 1) {
  12300. this._caps.instancedArrays = true;
  12301. }
  12302. else {
  12303. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12304. if (instanceExtension != null) {
  12305. this._caps.instancedArrays = true;
  12306. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12307. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12308. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12309. }
  12310. else {
  12311. this._caps.instancedArrays = false;
  12312. }
  12313. }
  12314. // Intelligently add supported compressed formats in order to check for.
  12315. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12316. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12317. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12318. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12319. if (this._caps.astc)
  12320. this.texturesSupported.push('-astc.ktx');
  12321. if (this._caps.s3tc)
  12322. this.texturesSupported.push('-dxt.ktx');
  12323. if (this._caps.pvrtc)
  12324. this.texturesSupported.push('-pvrtc.ktx');
  12325. if (this._caps.etc2)
  12326. this.texturesSupported.push('-etc2.ktx');
  12327. if (this._caps.etc1)
  12328. this.texturesSupported.push('-etc1.ktx');
  12329. if (this._gl.getShaderPrecisionFormat) {
  12330. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12331. if (highp) {
  12332. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12333. }
  12334. }
  12335. // Depth buffer
  12336. this.setDepthBuffer(true);
  12337. this.setDepthFunctionToLessOrEqual();
  12338. this.setDepthWrite(true);
  12339. // Texture maps
  12340. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12341. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12342. this._nextFreeTextureSlots.push(slot);
  12343. }
  12344. };
  12345. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12346. /**
  12347. * Gets version of the current webGL context
  12348. */
  12349. get: function () {
  12350. return this._webGLVersion;
  12351. },
  12352. enumerable: true,
  12353. configurable: true
  12354. });
  12355. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12356. /**
  12357. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12358. */
  12359. get: function () {
  12360. return this._isStencilEnable;
  12361. },
  12362. enumerable: true,
  12363. configurable: true
  12364. });
  12365. Engine.prototype._prepareWorkingCanvas = function () {
  12366. if (this._workingCanvas) {
  12367. return;
  12368. }
  12369. this._workingCanvas = document.createElement("canvas");
  12370. var context = this._workingCanvas.getContext("2d");
  12371. if (context) {
  12372. this._workingContext = context;
  12373. }
  12374. };
  12375. /**
  12376. * Reset the texture cache to empty state
  12377. */
  12378. Engine.prototype.resetTextureCache = function () {
  12379. for (var key in this._boundTexturesCache) {
  12380. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12381. continue;
  12382. }
  12383. var boundTexture = this._boundTexturesCache[key];
  12384. if (boundTexture) {
  12385. this._removeDesignatedSlot(boundTexture);
  12386. }
  12387. this._boundTexturesCache[key] = null;
  12388. }
  12389. if (!this.disableTextureBindingOptimization) {
  12390. this._nextFreeTextureSlots = [];
  12391. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12392. this._nextFreeTextureSlots.push(slot);
  12393. }
  12394. }
  12395. this._currentTextureChannel = -1;
  12396. };
  12397. /**
  12398. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12399. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12400. * @returns true if engine is in deterministic lock step mode
  12401. */
  12402. Engine.prototype.isDeterministicLockStep = function () {
  12403. return this._deterministicLockstep;
  12404. };
  12405. /**
  12406. * Gets the max steps when engine is running in deterministic lock step
  12407. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12408. * @returns the max steps
  12409. */
  12410. Engine.prototype.getLockstepMaxSteps = function () {
  12411. return this._lockstepMaxSteps;
  12412. };
  12413. /**
  12414. * Gets an object containing information about the current webGL context
  12415. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12416. */
  12417. Engine.prototype.getGlInfo = function () {
  12418. return {
  12419. vendor: this._glVendor,
  12420. renderer: this._glRenderer,
  12421. version: this._glVersion
  12422. };
  12423. };
  12424. /**
  12425. * Gets current aspect ratio
  12426. * @param camera defines the camera to use to get the aspect ratio
  12427. * @param useScreen defines if screen size must be used (or the current render target if any)
  12428. * @returns a number defining the aspect ratio
  12429. */
  12430. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12431. if (useScreen === void 0) { useScreen = false; }
  12432. var viewport = camera.viewport;
  12433. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12434. };
  12435. /**
  12436. * Gets current screen aspect ratio
  12437. * @returns a number defining the aspect ratio
  12438. */
  12439. Engine.prototype.getScreenAspectRatio = function () {
  12440. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12441. };
  12442. /**
  12443. * Gets the current render width
  12444. * @param useScreen defines if screen size must be used (or the current render target if any)
  12445. * @returns a number defining the current render width
  12446. */
  12447. Engine.prototype.getRenderWidth = function (useScreen) {
  12448. if (useScreen === void 0) { useScreen = false; }
  12449. if (!useScreen && this._currentRenderTarget) {
  12450. return this._currentRenderTarget.width;
  12451. }
  12452. return this._gl.drawingBufferWidth;
  12453. };
  12454. /**
  12455. * Gets the current render height
  12456. * @param useScreen defines if screen size must be used (or the current render target if any)
  12457. * @returns a number defining the current render height
  12458. */
  12459. Engine.prototype.getRenderHeight = function (useScreen) {
  12460. if (useScreen === void 0) { useScreen = false; }
  12461. if (!useScreen && this._currentRenderTarget) {
  12462. return this._currentRenderTarget.height;
  12463. }
  12464. return this._gl.drawingBufferHeight;
  12465. };
  12466. /**
  12467. * Gets the HTML canvas attached with the current webGL context
  12468. * @returns a HTML canvas
  12469. */
  12470. Engine.prototype.getRenderingCanvas = function () {
  12471. return this._renderingCanvas;
  12472. };
  12473. /**
  12474. * Gets the client rect of the HTML canvas attached with the current webGL context
  12475. * @returns a client rectanglee
  12476. */
  12477. Engine.prototype.getRenderingCanvasClientRect = function () {
  12478. if (!this._renderingCanvas) {
  12479. return null;
  12480. }
  12481. return this._renderingCanvas.getBoundingClientRect();
  12482. };
  12483. /**
  12484. * Defines the hardware scaling level.
  12485. * By default the hardware scaling level is computed from the window device ratio.
  12486. * 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.
  12487. * @param level defines the level to use
  12488. */
  12489. Engine.prototype.setHardwareScalingLevel = function (level) {
  12490. this._hardwareScalingLevel = level;
  12491. this.resize();
  12492. };
  12493. /**
  12494. * Gets the current hardware scaling level.
  12495. * By default the hardware scaling level is computed from the window device ratio.
  12496. * 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.
  12497. * @returns a number indicating the current hardware scaling level
  12498. */
  12499. Engine.prototype.getHardwareScalingLevel = function () {
  12500. return this._hardwareScalingLevel;
  12501. };
  12502. /**
  12503. * Gets the list of loaded textures
  12504. * @returns an array containing all loaded textures
  12505. */
  12506. Engine.prototype.getLoadedTexturesCache = function () {
  12507. return this._internalTexturesCache;
  12508. };
  12509. /**
  12510. * Gets the object containing all engine capabilities
  12511. * @returns the EngineCapabilities object
  12512. */
  12513. Engine.prototype.getCaps = function () {
  12514. return this._caps;
  12515. };
  12516. Object.defineProperty(Engine.prototype, "drawCalls", {
  12517. /** @hidden */
  12518. get: function () {
  12519. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12520. return 0;
  12521. },
  12522. enumerable: true,
  12523. configurable: true
  12524. });
  12525. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12526. /** @hidden */
  12527. get: function () {
  12528. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12529. return null;
  12530. },
  12531. enumerable: true,
  12532. configurable: true
  12533. });
  12534. /**
  12535. * Gets the current depth function
  12536. * @returns a number defining the depth function
  12537. */
  12538. Engine.prototype.getDepthFunction = function () {
  12539. return this._depthCullingState.depthFunc;
  12540. };
  12541. /**
  12542. * Sets the current depth function
  12543. * @param depthFunc defines the function to use
  12544. */
  12545. Engine.prototype.setDepthFunction = function (depthFunc) {
  12546. this._depthCullingState.depthFunc = depthFunc;
  12547. };
  12548. /**
  12549. * Sets the current depth function to GREATER
  12550. */
  12551. Engine.prototype.setDepthFunctionToGreater = function () {
  12552. this._depthCullingState.depthFunc = this._gl.GREATER;
  12553. };
  12554. /**
  12555. * Sets the current depth function to GEQUAL
  12556. */
  12557. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12558. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12559. };
  12560. /**
  12561. * Sets the current depth function to LESS
  12562. */
  12563. Engine.prototype.setDepthFunctionToLess = function () {
  12564. this._depthCullingState.depthFunc = this._gl.LESS;
  12565. };
  12566. /**
  12567. * Sets the current depth function to LEQUAL
  12568. */
  12569. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12570. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12571. };
  12572. /**
  12573. * Gets a boolean indicating if stencil buffer is enabled
  12574. * @returns the current stencil buffer state
  12575. */
  12576. Engine.prototype.getStencilBuffer = function () {
  12577. return this._stencilState.stencilTest;
  12578. };
  12579. /**
  12580. * Enable or disable the stencil buffer
  12581. * @param enable defines if the stencil buffer must be enabled or disabled
  12582. */
  12583. Engine.prototype.setStencilBuffer = function (enable) {
  12584. this._stencilState.stencilTest = enable;
  12585. };
  12586. /**
  12587. * Gets the current stencil mask
  12588. * @returns a number defining the new stencil mask to use
  12589. */
  12590. Engine.prototype.getStencilMask = function () {
  12591. return this._stencilState.stencilMask;
  12592. };
  12593. /**
  12594. * Sets the current stencil mask
  12595. * @param mask defines the new stencil mask to use
  12596. */
  12597. Engine.prototype.setStencilMask = function (mask) {
  12598. this._stencilState.stencilMask = mask;
  12599. };
  12600. /**
  12601. * Gets the current stencil function
  12602. * @returns a number defining the stencil function to use
  12603. */
  12604. Engine.prototype.getStencilFunction = function () {
  12605. return this._stencilState.stencilFunc;
  12606. };
  12607. /**
  12608. * Gets the current stencil reference value
  12609. * @returns a number defining the stencil reference value to use
  12610. */
  12611. Engine.prototype.getStencilFunctionReference = function () {
  12612. return this._stencilState.stencilFuncRef;
  12613. };
  12614. /**
  12615. * Gets the current stencil mask
  12616. * @returns a number defining the stencil mask to use
  12617. */
  12618. Engine.prototype.getStencilFunctionMask = function () {
  12619. return this._stencilState.stencilFuncMask;
  12620. };
  12621. /**
  12622. * Sets the current stencil function
  12623. * @param stencilFunc defines the new stencil function to use
  12624. */
  12625. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12626. this._stencilState.stencilFunc = stencilFunc;
  12627. };
  12628. /**
  12629. * Sets the current stencil reference
  12630. * @param reference defines the new stencil reference to use
  12631. */
  12632. Engine.prototype.setStencilFunctionReference = function (reference) {
  12633. this._stencilState.stencilFuncRef = reference;
  12634. };
  12635. /**
  12636. * Sets the current stencil mask
  12637. * @param mask defines the new stencil mask to use
  12638. */
  12639. Engine.prototype.setStencilFunctionMask = function (mask) {
  12640. this._stencilState.stencilFuncMask = mask;
  12641. };
  12642. /**
  12643. * Gets the current stencil operation when stencil fails
  12644. * @returns a number defining stencil operation to use when stencil fails
  12645. */
  12646. Engine.prototype.getStencilOperationFail = function () {
  12647. return this._stencilState.stencilOpStencilFail;
  12648. };
  12649. /**
  12650. * Gets the current stencil operation when depth fails
  12651. * @returns a number defining stencil operation to use when depth fails
  12652. */
  12653. Engine.prototype.getStencilOperationDepthFail = function () {
  12654. return this._stencilState.stencilOpDepthFail;
  12655. };
  12656. /**
  12657. * Gets the current stencil operation when stencil passes
  12658. * @returns a number defining stencil operation to use when stencil passes
  12659. */
  12660. Engine.prototype.getStencilOperationPass = function () {
  12661. return this._stencilState.stencilOpStencilDepthPass;
  12662. };
  12663. /**
  12664. * Sets the stencil operation to use when stencil fails
  12665. * @param operation defines the stencil operation to use when stencil fails
  12666. */
  12667. Engine.prototype.setStencilOperationFail = function (operation) {
  12668. this._stencilState.stencilOpStencilFail = operation;
  12669. };
  12670. /**
  12671. * Sets the stencil operation to use when depth fails
  12672. * @param operation defines the stencil operation to use when depth fails
  12673. */
  12674. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12675. this._stencilState.stencilOpDepthFail = operation;
  12676. };
  12677. /**
  12678. * Sets the stencil operation to use when stencil passes
  12679. * @param operation defines the stencil operation to use when stencil passes
  12680. */
  12681. Engine.prototype.setStencilOperationPass = function (operation) {
  12682. this._stencilState.stencilOpStencilDepthPass = operation;
  12683. };
  12684. /**
  12685. * Sets a boolean indicating if the dithering state is enabled or disabled
  12686. * @param value defines the dithering state
  12687. */
  12688. Engine.prototype.setDitheringState = function (value) {
  12689. if (value) {
  12690. this._gl.enable(this._gl.DITHER);
  12691. }
  12692. else {
  12693. this._gl.disable(this._gl.DITHER);
  12694. }
  12695. };
  12696. /**
  12697. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12698. * @param value defines the rasterizer state
  12699. */
  12700. Engine.prototype.setRasterizerState = function (value) {
  12701. if (value) {
  12702. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12703. }
  12704. else {
  12705. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12706. }
  12707. };
  12708. /**
  12709. * stop executing a render loop function and remove it from the execution array
  12710. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12711. */
  12712. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12713. if (!renderFunction) {
  12714. this._activeRenderLoops = [];
  12715. return;
  12716. }
  12717. var index = this._activeRenderLoops.indexOf(renderFunction);
  12718. if (index >= 0) {
  12719. this._activeRenderLoops.splice(index, 1);
  12720. }
  12721. };
  12722. /** @hidden */
  12723. Engine.prototype._renderLoop = function () {
  12724. if (!this._contextWasLost) {
  12725. var shouldRender = true;
  12726. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12727. shouldRender = false;
  12728. }
  12729. if (shouldRender) {
  12730. // Start new frame
  12731. this.beginFrame();
  12732. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12733. var renderFunction = this._activeRenderLoops[index];
  12734. renderFunction();
  12735. }
  12736. // Present
  12737. this.endFrame();
  12738. }
  12739. }
  12740. if (this._activeRenderLoops.length > 0) {
  12741. // Register new frame
  12742. var requester = null;
  12743. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12744. requester = this._vrDisplay;
  12745. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12746. }
  12747. else {
  12748. this._renderingQueueLaunched = false;
  12749. }
  12750. };
  12751. /**
  12752. * Register and execute a render loop. The engine can have more than one render function
  12753. * @param renderFunction defines the function to continuously execute
  12754. */
  12755. Engine.prototype.runRenderLoop = function (renderFunction) {
  12756. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12757. return;
  12758. }
  12759. this._activeRenderLoops.push(renderFunction);
  12760. if (!this._renderingQueueLaunched) {
  12761. this._renderingQueueLaunched = true;
  12762. this._bindedRenderFunction = this._renderLoop.bind(this);
  12763. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12764. }
  12765. };
  12766. /**
  12767. * Toggle full screen mode
  12768. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12769. * @param options defines an option object to be sent to the requestFullscreen function
  12770. */
  12771. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12772. if (this.isFullscreen) {
  12773. BABYLON.Tools.ExitFullscreen();
  12774. }
  12775. else {
  12776. this._pointerLockRequested = requestPointerLock;
  12777. if (this._renderingCanvas) {
  12778. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12779. }
  12780. }
  12781. };
  12782. /**
  12783. * Clear the current render buffer or the current render target (if any is set up)
  12784. * @param color defines the color to use
  12785. * @param backBuffer defines if the back buffer must be cleared
  12786. * @param depth defines if the depth buffer must be cleared
  12787. * @param stencil defines if the stencil buffer must be cleared
  12788. */
  12789. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12790. if (stencil === void 0) { stencil = false; }
  12791. this.applyStates();
  12792. var mode = 0;
  12793. if (backBuffer && color) {
  12794. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12795. mode |= this._gl.COLOR_BUFFER_BIT;
  12796. }
  12797. if (depth) {
  12798. this._gl.clearDepth(1.0);
  12799. mode |= this._gl.DEPTH_BUFFER_BIT;
  12800. }
  12801. if (stencil) {
  12802. this._gl.clearStencil(0);
  12803. mode |= this._gl.STENCIL_BUFFER_BIT;
  12804. }
  12805. this._gl.clear(mode);
  12806. };
  12807. /**
  12808. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12809. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12810. * @param y defines the y-coordinate of the corner of the clear rectangle
  12811. * @param width defines the width of the clear rectangle
  12812. * @param height defines the height of the clear rectangle
  12813. * @param clearColor defines the clear color
  12814. */
  12815. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12816. var gl = this._gl;
  12817. // Save state
  12818. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12819. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12820. // Change state
  12821. gl.enable(gl.SCISSOR_TEST);
  12822. gl.scissor(x, y, width, height);
  12823. // Clear
  12824. this.clear(clearColor, true, true, true);
  12825. // Restore state
  12826. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12827. if (curScissor === true) {
  12828. gl.enable(gl.SCISSOR_TEST);
  12829. }
  12830. else {
  12831. gl.disable(gl.SCISSOR_TEST);
  12832. }
  12833. };
  12834. /** @hidden */
  12835. Engine.prototype._viewport = function (x, y, width, height) {
  12836. if (x !== this._viewportCached.x ||
  12837. y !== this._viewportCached.y ||
  12838. width !== this._viewportCached.z ||
  12839. height !== this._viewportCached.w) {
  12840. this._viewportCached.x = x;
  12841. this._viewportCached.y = y;
  12842. this._viewportCached.z = width;
  12843. this._viewportCached.w = height;
  12844. this._gl.viewport(x, y, width, height);
  12845. }
  12846. };
  12847. /**
  12848. * Set the WebGL's viewport
  12849. * @param viewport defines the viewport element to be used
  12850. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12851. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12852. */
  12853. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12854. var width = requiredWidth || this.getRenderWidth();
  12855. var height = requiredHeight || this.getRenderHeight();
  12856. var x = viewport.x || 0;
  12857. var y = viewport.y || 0;
  12858. this._cachedViewport = viewport;
  12859. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12860. };
  12861. /**
  12862. * Directly set the WebGL Viewport
  12863. * @param x defines the x coordinate of the viewport (in screen space)
  12864. * @param y defines the y coordinate of the viewport (in screen space)
  12865. * @param width defines the width of the viewport (in screen space)
  12866. * @param height defines the height of the viewport (in screen space)
  12867. * @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
  12868. */
  12869. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12870. var currentViewport = this._cachedViewport;
  12871. this._cachedViewport = null;
  12872. this._viewport(x, y, width, height);
  12873. return currentViewport;
  12874. };
  12875. /**
  12876. * Begin a new frame
  12877. */
  12878. Engine.prototype.beginFrame = function () {
  12879. this.onBeginFrameObservable.notifyObservers(this);
  12880. this._measureFps();
  12881. };
  12882. /**
  12883. * Enf the current frame
  12884. */
  12885. Engine.prototype.endFrame = function () {
  12886. // Force a flush in case we are using a bad OS.
  12887. if (this._badOS) {
  12888. this.flushFramebuffer();
  12889. }
  12890. // Submit frame to the vr device, if enabled
  12891. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12892. // TODO: We should only submit the frame if we read frameData successfully.
  12893. this._vrDisplay.submitFrame();
  12894. }
  12895. this.onEndFrameObservable.notifyObservers(this);
  12896. };
  12897. /**
  12898. * Resize the view according to the canvas' size
  12899. */
  12900. Engine.prototype.resize = function () {
  12901. // We're not resizing the size of the canvas while in VR mode & presenting
  12902. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12903. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12904. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12905. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12906. }
  12907. };
  12908. /**
  12909. * Force a specific size of the canvas
  12910. * @param width defines the new canvas' width
  12911. * @param height defines the new canvas' height
  12912. */
  12913. Engine.prototype.setSize = function (width, height) {
  12914. if (!this._renderingCanvas) {
  12915. return;
  12916. }
  12917. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12918. return;
  12919. }
  12920. this._renderingCanvas.width = width;
  12921. this._renderingCanvas.height = height;
  12922. for (var index = 0; index < this.scenes.length; index++) {
  12923. var scene = this.scenes[index];
  12924. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12925. var cam = scene.cameras[camIndex];
  12926. cam._currentRenderId = 0;
  12927. }
  12928. }
  12929. if (this.onResizeObservable.hasObservers) {
  12930. this.onResizeObservable.notifyObservers(this);
  12931. }
  12932. };
  12933. // WebVR functions
  12934. /**
  12935. * Gets a boolean indicating if a webVR device was detected
  12936. * @returns true if a webVR device was detected
  12937. */
  12938. Engine.prototype.isVRDevicePresent = function () {
  12939. return !!this._vrDisplay;
  12940. };
  12941. /**
  12942. * Gets the current webVR device
  12943. * @returns the current webVR device (or null)
  12944. */
  12945. Engine.prototype.getVRDevice = function () {
  12946. return this._vrDisplay;
  12947. };
  12948. /**
  12949. * Initializes a webVR display and starts listening to display change events
  12950. * The onVRDisplayChangedObservable will be notified upon these changes
  12951. * @returns The onVRDisplayChangedObservable
  12952. */
  12953. Engine.prototype.initWebVR = function () {
  12954. this.initWebVRAsync();
  12955. return this.onVRDisplayChangedObservable;
  12956. };
  12957. /**
  12958. * Initializes a webVR display and starts listening to display change events
  12959. * The onVRDisplayChangedObservable will be notified upon these changes
  12960. * @returns A promise containing a VRDisplay and if vr is supported
  12961. */
  12962. Engine.prototype.initWebVRAsync = function () {
  12963. var _this = this;
  12964. var notifyObservers = function () {
  12965. var eventArgs = {
  12966. vrDisplay: _this._vrDisplay,
  12967. vrSupported: _this._vrSupported
  12968. };
  12969. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12970. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12971. };
  12972. if (!this._onVrDisplayConnect) {
  12973. this._onVrDisplayConnect = function (event) {
  12974. _this._vrDisplay = event.display;
  12975. notifyObservers();
  12976. };
  12977. this._onVrDisplayDisconnect = function () {
  12978. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12979. _this._vrDisplay = undefined;
  12980. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12981. notifyObservers();
  12982. };
  12983. this._onVrDisplayPresentChange = function () {
  12984. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12985. };
  12986. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12987. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12988. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12989. }
  12990. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12991. this._webVRInitPromise.then(notifyObservers);
  12992. return this._webVRInitPromise;
  12993. };
  12994. /**
  12995. * Call this function to switch to webVR mode
  12996. * Will do nothing if webVR is not supported or if there is no webVR device
  12997. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12998. */
  12999. Engine.prototype.enableVR = function () {
  13000. var _this = this;
  13001. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13002. var onResolved = function () {
  13003. _this.onVRRequestPresentComplete.notifyObservers(true);
  13004. _this._onVRFullScreenTriggered();
  13005. };
  13006. var onRejected = function () {
  13007. _this.onVRRequestPresentComplete.notifyObservers(false);
  13008. };
  13009. this.onVRRequestPresentStart.notifyObservers(this);
  13010. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13011. }
  13012. };
  13013. /**
  13014. * Call this function to leave webVR mode
  13015. * Will do nothing if webVR is not supported or if there is no webVR device
  13016. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13017. */
  13018. Engine.prototype.disableVR = function () {
  13019. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13020. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13021. }
  13022. };
  13023. Engine.prototype._getVRDisplaysAsync = function () {
  13024. var _this = this;
  13025. return new Promise(function (res, rej) {
  13026. if (navigator.getVRDisplays) {
  13027. navigator.getVRDisplays().then(function (devices) {
  13028. _this._vrSupported = true;
  13029. // note that devices may actually be an empty array. This is fine;
  13030. // we expect this._vrDisplay to be undefined in this case.
  13031. _this._vrDisplay = devices[0];
  13032. res({
  13033. vrDisplay: _this._vrDisplay,
  13034. vrSupported: _this._vrSupported
  13035. });
  13036. });
  13037. }
  13038. else {
  13039. _this._vrDisplay = undefined;
  13040. _this._vrSupported = false;
  13041. res({
  13042. vrDisplay: _this._vrDisplay,
  13043. vrSupported: _this._vrSupported
  13044. });
  13045. }
  13046. });
  13047. };
  13048. /**
  13049. * Binds the frame buffer to the specified texture.
  13050. * @param texture The texture to render to or null for the default canvas
  13051. * @param faceIndex The face of the texture to render to in case of cube texture
  13052. * @param requiredWidth The width of the target to render to
  13053. * @param requiredHeight The height of the target to render to
  13054. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13055. * @param depthStencilTexture The depth stencil texture to use to render
  13056. * @param lodLevel defines le lod level to bind to the frame buffer
  13057. */
  13058. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13059. if (lodLevel === void 0) { lodLevel = 0; }
  13060. if (this._currentRenderTarget) {
  13061. this.unBindFramebuffer(this._currentRenderTarget);
  13062. }
  13063. this._currentRenderTarget = texture;
  13064. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13065. var gl = this._gl;
  13066. if (texture.isCube) {
  13067. if (faceIndex === undefined) {
  13068. faceIndex = 0;
  13069. }
  13070. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13071. if (depthStencilTexture) {
  13072. if (depthStencilTexture._generateStencilBuffer) {
  13073. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13074. }
  13075. else {
  13076. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13077. }
  13078. }
  13079. }
  13080. if (this._cachedViewport && !forceFullscreenViewport) {
  13081. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13082. }
  13083. else {
  13084. if (!requiredWidth) {
  13085. requiredWidth = texture.width;
  13086. if (lodLevel) {
  13087. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13088. }
  13089. }
  13090. if (!requiredHeight) {
  13091. requiredHeight = texture.height;
  13092. if (lodLevel) {
  13093. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13094. }
  13095. }
  13096. this._viewport(0, 0, requiredWidth, requiredHeight);
  13097. }
  13098. this.wipeCaches();
  13099. };
  13100. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13101. if (this._currentFramebuffer !== framebuffer) {
  13102. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13103. this._currentFramebuffer = framebuffer;
  13104. }
  13105. };
  13106. /**
  13107. * Unbind the current render target texture from the webGL context
  13108. * @param texture defines the render target texture to unbind
  13109. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13110. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13111. */
  13112. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13113. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13114. this._currentRenderTarget = null;
  13115. // If MSAA, we need to bitblt back to main texture
  13116. var gl = this._gl;
  13117. if (texture._MSAAFramebuffer) {
  13118. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13119. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13120. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13121. }
  13122. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13123. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13124. gl.generateMipmap(gl.TEXTURE_2D);
  13125. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13126. }
  13127. if (onBeforeUnbind) {
  13128. if (texture._MSAAFramebuffer) {
  13129. // Bind the correct framebuffer
  13130. this.bindUnboundFramebuffer(texture._framebuffer);
  13131. }
  13132. onBeforeUnbind();
  13133. }
  13134. this.bindUnboundFramebuffer(null);
  13135. };
  13136. /**
  13137. * Unbind a list of render target textures from the webGL context
  13138. * This is used only when drawBuffer extension or webGL2 are active
  13139. * @param textures defines the render target textures to unbind
  13140. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13141. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13142. */
  13143. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13144. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13145. this._currentRenderTarget = null;
  13146. // If MSAA, we need to bitblt back to main texture
  13147. var gl = this._gl;
  13148. if (textures[0]._MSAAFramebuffer) {
  13149. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13150. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13151. var attachments = textures[0]._attachments;
  13152. if (!attachments) {
  13153. attachments = new Array(textures.length);
  13154. textures[0]._attachments = attachments;
  13155. }
  13156. for (var i = 0; i < textures.length; i++) {
  13157. var texture = textures[i];
  13158. for (var j = 0; j < attachments.length; j++) {
  13159. attachments[j] = gl.NONE;
  13160. }
  13161. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13162. gl.readBuffer(attachments[i]);
  13163. gl.drawBuffers(attachments);
  13164. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13165. }
  13166. for (var i = 0; i < attachments.length; i++) {
  13167. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13168. }
  13169. gl.drawBuffers(attachments);
  13170. }
  13171. for (var i = 0; i < textures.length; i++) {
  13172. var texture = textures[i];
  13173. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13174. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13175. gl.generateMipmap(gl.TEXTURE_2D);
  13176. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13177. }
  13178. }
  13179. if (onBeforeUnbind) {
  13180. if (textures[0]._MSAAFramebuffer) {
  13181. // Bind the correct framebuffer
  13182. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13183. }
  13184. onBeforeUnbind();
  13185. }
  13186. this.bindUnboundFramebuffer(null);
  13187. };
  13188. /**
  13189. * Force the mipmap generation for the given render target texture
  13190. * @param texture defines the render target texture to use
  13191. */
  13192. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13193. if (texture.generateMipMaps) {
  13194. var gl = this._gl;
  13195. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13196. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13197. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13198. }
  13199. };
  13200. /**
  13201. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13202. */
  13203. Engine.prototype.flushFramebuffer = function () {
  13204. this._gl.flush();
  13205. };
  13206. /**
  13207. * Unbind the current render target and bind the default framebuffer
  13208. */
  13209. Engine.prototype.restoreDefaultFramebuffer = function () {
  13210. if (this._currentRenderTarget) {
  13211. this.unBindFramebuffer(this._currentRenderTarget);
  13212. }
  13213. else {
  13214. this.bindUnboundFramebuffer(null);
  13215. }
  13216. if (this._cachedViewport) {
  13217. this.setViewport(this._cachedViewport);
  13218. }
  13219. this.wipeCaches();
  13220. };
  13221. // UBOs
  13222. /**
  13223. * Create an uniform buffer
  13224. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13225. * @param elements defines the content of the uniform buffer
  13226. * @returns the webGL uniform buffer
  13227. */
  13228. Engine.prototype.createUniformBuffer = function (elements) {
  13229. var ubo = this._gl.createBuffer();
  13230. if (!ubo) {
  13231. throw new Error("Unable to create uniform buffer");
  13232. }
  13233. this.bindUniformBuffer(ubo);
  13234. if (elements instanceof Float32Array) {
  13235. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13236. }
  13237. else {
  13238. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13239. }
  13240. this.bindUniformBuffer(null);
  13241. ubo.references = 1;
  13242. return ubo;
  13243. };
  13244. /**
  13245. * Create a dynamic uniform buffer
  13246. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13247. * @param elements defines the content of the uniform buffer
  13248. * @returns the webGL uniform buffer
  13249. */
  13250. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13251. var ubo = this._gl.createBuffer();
  13252. if (!ubo) {
  13253. throw new Error("Unable to create dynamic uniform buffer");
  13254. }
  13255. this.bindUniformBuffer(ubo);
  13256. if (elements instanceof Float32Array) {
  13257. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13258. }
  13259. else {
  13260. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13261. }
  13262. this.bindUniformBuffer(null);
  13263. ubo.references = 1;
  13264. return ubo;
  13265. };
  13266. /**
  13267. * Update an existing uniform buffer
  13268. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13269. * @param uniformBuffer defines the target uniform buffer
  13270. * @param elements defines the content to update
  13271. * @param offset defines the offset in the uniform buffer where update should start
  13272. * @param count defines the size of the data to update
  13273. */
  13274. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13275. this.bindUniformBuffer(uniformBuffer);
  13276. if (offset === undefined) {
  13277. offset = 0;
  13278. }
  13279. if (count === undefined) {
  13280. if (elements instanceof Float32Array) {
  13281. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13282. }
  13283. else {
  13284. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13285. }
  13286. }
  13287. else {
  13288. if (elements instanceof Float32Array) {
  13289. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13290. }
  13291. else {
  13292. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13293. }
  13294. }
  13295. this.bindUniformBuffer(null);
  13296. };
  13297. // VBOs
  13298. Engine.prototype._resetVertexBufferBinding = function () {
  13299. this.bindArrayBuffer(null);
  13300. this._cachedVertexBuffers = null;
  13301. };
  13302. /**
  13303. * Creates a vertex buffer
  13304. * @param data the data for the vertex buffer
  13305. * @returns the new WebGL static buffer
  13306. */
  13307. Engine.prototype.createVertexBuffer = function (data) {
  13308. var vbo = this._gl.createBuffer();
  13309. if (!vbo) {
  13310. throw new Error("Unable to create vertex buffer");
  13311. }
  13312. this.bindArrayBuffer(vbo);
  13313. if (data instanceof Array) {
  13314. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13315. }
  13316. else {
  13317. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13318. }
  13319. this._resetVertexBufferBinding();
  13320. vbo.references = 1;
  13321. return vbo;
  13322. };
  13323. /**
  13324. * Creates a dynamic vertex buffer
  13325. * @param data the data for the dynamic vertex buffer
  13326. * @returns the new WebGL dynamic buffer
  13327. */
  13328. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13329. var vbo = this._gl.createBuffer();
  13330. if (!vbo) {
  13331. throw new Error("Unable to create dynamic vertex buffer");
  13332. }
  13333. this.bindArrayBuffer(vbo);
  13334. if (data instanceof Array) {
  13335. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13336. }
  13337. else {
  13338. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13339. }
  13340. this._resetVertexBufferBinding();
  13341. vbo.references = 1;
  13342. return vbo;
  13343. };
  13344. /**
  13345. * Update a dynamic index buffer
  13346. * @param indexBuffer defines the target index buffer
  13347. * @param indices defines the data to update
  13348. * @param offset defines the offset in the target index buffer where update should start
  13349. */
  13350. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13351. if (offset === void 0) { offset = 0; }
  13352. // Force cache update
  13353. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13354. this.bindIndexBuffer(indexBuffer);
  13355. var arrayBuffer;
  13356. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13357. arrayBuffer = indices;
  13358. }
  13359. else {
  13360. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13361. }
  13362. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13363. this._resetIndexBufferBinding();
  13364. };
  13365. /**
  13366. * Updates a dynamic vertex buffer.
  13367. * @param vertexBuffer the vertex buffer to update
  13368. * @param data the data used to update the vertex buffer
  13369. * @param byteOffset the byte offset of the data
  13370. * @param byteLength the byte length of the data
  13371. */
  13372. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13373. this.bindArrayBuffer(vertexBuffer);
  13374. if (byteOffset === undefined) {
  13375. byteOffset = 0;
  13376. }
  13377. if (byteLength === undefined) {
  13378. if (data instanceof Array) {
  13379. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13380. }
  13381. else {
  13382. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13383. }
  13384. }
  13385. else {
  13386. if (data instanceof Array) {
  13387. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13388. }
  13389. else {
  13390. if (data instanceof ArrayBuffer) {
  13391. data = new Uint8Array(data, byteOffset, byteLength);
  13392. }
  13393. else {
  13394. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13395. }
  13396. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13397. }
  13398. }
  13399. this._resetVertexBufferBinding();
  13400. };
  13401. Engine.prototype._resetIndexBufferBinding = function () {
  13402. this.bindIndexBuffer(null);
  13403. this._cachedIndexBuffer = null;
  13404. };
  13405. /**
  13406. * Creates a new index buffer
  13407. * @param indices defines the content of the index buffer
  13408. * @param updatable defines if the index buffer must be updatable
  13409. * @returns a new webGL buffer
  13410. */
  13411. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13412. var vbo = this._gl.createBuffer();
  13413. if (!vbo) {
  13414. throw new Error("Unable to create index buffer");
  13415. }
  13416. this.bindIndexBuffer(vbo);
  13417. // Check for 32 bits indices
  13418. var arrayBuffer;
  13419. var need32Bits = false;
  13420. if (indices instanceof Uint16Array) {
  13421. arrayBuffer = indices;
  13422. }
  13423. else {
  13424. //check 32 bit support
  13425. if (this._caps.uintIndices) {
  13426. if (indices instanceof Uint32Array) {
  13427. arrayBuffer = indices;
  13428. need32Bits = true;
  13429. }
  13430. else {
  13431. //number[] or Int32Array, check if 32 bit is necessary
  13432. for (var index = 0; index < indices.length; index++) {
  13433. if (indices[index] > 65535) {
  13434. need32Bits = true;
  13435. break;
  13436. }
  13437. }
  13438. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13439. }
  13440. }
  13441. else {
  13442. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13443. arrayBuffer = new Uint16Array(indices);
  13444. }
  13445. }
  13446. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13447. this._resetIndexBufferBinding();
  13448. vbo.references = 1;
  13449. vbo.is32Bits = need32Bits;
  13450. return vbo;
  13451. };
  13452. /**
  13453. * Bind a webGL buffer to the webGL context
  13454. * @param buffer defines the buffer to bind
  13455. */
  13456. Engine.prototype.bindArrayBuffer = function (buffer) {
  13457. if (!this._vaoRecordInProgress) {
  13458. this._unbindVertexArrayObject();
  13459. }
  13460. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13461. };
  13462. /**
  13463. * Bind an uniform buffer to the current webGL context
  13464. * @param buffer defines the buffer to bind
  13465. */
  13466. Engine.prototype.bindUniformBuffer = function (buffer) {
  13467. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13468. };
  13469. /**
  13470. * Bind a buffer to the current webGL context at a given location
  13471. * @param buffer defines the buffer to bind
  13472. * @param location defines the index where to bind the buffer
  13473. */
  13474. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13475. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13476. };
  13477. /**
  13478. * Bind a specific block at a given index in a specific shader program
  13479. * @param shaderProgram defines the shader program
  13480. * @param blockName defines the block name
  13481. * @param index defines the index where to bind the block
  13482. */
  13483. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13484. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13485. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13486. };
  13487. ;
  13488. Engine.prototype.bindIndexBuffer = function (buffer) {
  13489. if (!this._vaoRecordInProgress) {
  13490. this._unbindVertexArrayObject();
  13491. }
  13492. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13493. };
  13494. Engine.prototype.bindBuffer = function (buffer, target) {
  13495. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13496. this._gl.bindBuffer(target, buffer);
  13497. this._currentBoundBuffer[target] = buffer;
  13498. }
  13499. };
  13500. /**
  13501. * update the bound buffer with the given data
  13502. * @param data defines the data to update
  13503. */
  13504. Engine.prototype.updateArrayBuffer = function (data) {
  13505. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13506. };
  13507. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13508. var pointer = this._currentBufferPointers[indx];
  13509. var changed = false;
  13510. if (!pointer.active) {
  13511. changed = true;
  13512. pointer.active = true;
  13513. pointer.index = indx;
  13514. pointer.size = size;
  13515. pointer.type = type;
  13516. pointer.normalized = normalized;
  13517. pointer.stride = stride;
  13518. pointer.offset = offset;
  13519. pointer.buffer = buffer;
  13520. }
  13521. else {
  13522. if (pointer.buffer !== buffer) {
  13523. pointer.buffer = buffer;
  13524. changed = true;
  13525. }
  13526. if (pointer.size !== size) {
  13527. pointer.size = size;
  13528. changed = true;
  13529. }
  13530. if (pointer.type !== type) {
  13531. pointer.type = type;
  13532. changed = true;
  13533. }
  13534. if (pointer.normalized !== normalized) {
  13535. pointer.normalized = normalized;
  13536. changed = true;
  13537. }
  13538. if (pointer.stride !== stride) {
  13539. pointer.stride = stride;
  13540. changed = true;
  13541. }
  13542. if (pointer.offset !== offset) {
  13543. pointer.offset = offset;
  13544. changed = true;
  13545. }
  13546. }
  13547. if (changed || this._vaoRecordInProgress) {
  13548. this.bindArrayBuffer(buffer);
  13549. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13550. }
  13551. };
  13552. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13553. if (indexBuffer == null) {
  13554. return;
  13555. }
  13556. if (this._cachedIndexBuffer !== indexBuffer) {
  13557. this._cachedIndexBuffer = indexBuffer;
  13558. this.bindIndexBuffer(indexBuffer);
  13559. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13560. }
  13561. };
  13562. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13563. var attributes = effect.getAttributesNames();
  13564. if (!this._vaoRecordInProgress) {
  13565. this._unbindVertexArrayObject();
  13566. }
  13567. this.unbindAllAttributes();
  13568. for (var index = 0; index < attributes.length; index++) {
  13569. var order = effect.getAttributeLocation(index);
  13570. if (order >= 0) {
  13571. var vertexBuffer = vertexBuffers[attributes[index]];
  13572. if (!vertexBuffer) {
  13573. continue;
  13574. }
  13575. this._gl.enableVertexAttribArray(order);
  13576. if (!this._vaoRecordInProgress) {
  13577. this._vertexAttribArraysEnabled[order] = true;
  13578. }
  13579. var buffer = vertexBuffer.getBuffer();
  13580. if (buffer) {
  13581. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13582. if (vertexBuffer.getIsInstanced()) {
  13583. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13584. if (!this._vaoRecordInProgress) {
  13585. this._currentInstanceLocations.push(order);
  13586. this._currentInstanceBuffers.push(buffer);
  13587. }
  13588. }
  13589. }
  13590. }
  13591. }
  13592. };
  13593. /**
  13594. * Records a vertex array object
  13595. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13596. * @param vertexBuffers defines the list of vertex buffers to store
  13597. * @param indexBuffer defines the index buffer to store
  13598. * @param effect defines the effect to store
  13599. * @returns the new vertex array object
  13600. */
  13601. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13602. var vao = this._gl.createVertexArray();
  13603. this._vaoRecordInProgress = true;
  13604. this._gl.bindVertexArray(vao);
  13605. this._mustWipeVertexAttributes = true;
  13606. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13607. this.bindIndexBuffer(indexBuffer);
  13608. this._vaoRecordInProgress = false;
  13609. this._gl.bindVertexArray(null);
  13610. return vao;
  13611. };
  13612. /**
  13613. * Bind a specific vertex array object
  13614. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13615. * @param vertexArrayObject defines the vertex array object to bind
  13616. * @param indexBuffer defines the index buffer to bind
  13617. */
  13618. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13619. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13620. this._cachedVertexArrayObject = vertexArrayObject;
  13621. this._gl.bindVertexArray(vertexArrayObject);
  13622. this._cachedVertexBuffers = null;
  13623. this._cachedIndexBuffer = null;
  13624. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13625. this._mustWipeVertexAttributes = true;
  13626. }
  13627. };
  13628. /**
  13629. * Bind webGl buffers directly to the webGL context
  13630. * @param vertexBuffer defines the vertex buffer to bind
  13631. * @param indexBuffer defines the index buffer to bind
  13632. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13633. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13634. * @param effect defines the effect associated with the vertex buffer
  13635. */
  13636. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13637. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13638. this._cachedVertexBuffers = vertexBuffer;
  13639. this._cachedEffectForVertexBuffers = effect;
  13640. var attributesCount = effect.getAttributesCount();
  13641. this._unbindVertexArrayObject();
  13642. this.unbindAllAttributes();
  13643. var offset = 0;
  13644. for (var index = 0; index < attributesCount; index++) {
  13645. if (index < vertexDeclaration.length) {
  13646. var order = effect.getAttributeLocation(index);
  13647. if (order >= 0) {
  13648. this._gl.enableVertexAttribArray(order);
  13649. this._vertexAttribArraysEnabled[order] = true;
  13650. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13651. }
  13652. offset += vertexDeclaration[index] * 4;
  13653. }
  13654. }
  13655. }
  13656. this._bindIndexBufferWithCache(indexBuffer);
  13657. };
  13658. Engine.prototype._unbindVertexArrayObject = function () {
  13659. if (!this._cachedVertexArrayObject) {
  13660. return;
  13661. }
  13662. this._cachedVertexArrayObject = null;
  13663. this._gl.bindVertexArray(null);
  13664. };
  13665. /**
  13666. * Bind a list of vertex buffers to the webGL context
  13667. * @param vertexBuffers defines the list of vertex buffers to bind
  13668. * @param indexBuffer defines the index buffer to bind
  13669. * @param effect defines the effect associated with the vertex buffers
  13670. */
  13671. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13672. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13673. this._cachedVertexBuffers = vertexBuffers;
  13674. this._cachedEffectForVertexBuffers = effect;
  13675. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13676. }
  13677. this._bindIndexBufferWithCache(indexBuffer);
  13678. };
  13679. /**
  13680. * Unbind all instance attributes
  13681. */
  13682. Engine.prototype.unbindInstanceAttributes = function () {
  13683. var boundBuffer;
  13684. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13685. var instancesBuffer = this._currentInstanceBuffers[i];
  13686. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13687. boundBuffer = instancesBuffer;
  13688. this.bindArrayBuffer(instancesBuffer);
  13689. }
  13690. var offsetLocation = this._currentInstanceLocations[i];
  13691. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13692. }
  13693. this._currentInstanceBuffers.length = 0;
  13694. this._currentInstanceLocations.length = 0;
  13695. };
  13696. /**
  13697. * Release and free the memory of a vertex array object
  13698. * @param vao defines the vertex array object to delete
  13699. */
  13700. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13701. this._gl.deleteVertexArray(vao);
  13702. };
  13703. /** @hidden */
  13704. Engine.prototype._releaseBuffer = function (buffer) {
  13705. buffer.references--;
  13706. if (buffer.references === 0) {
  13707. this._gl.deleteBuffer(buffer);
  13708. return true;
  13709. }
  13710. return false;
  13711. };
  13712. /**
  13713. * Creates a webGL buffer to use with instanciation
  13714. * @param capacity defines the size of the buffer
  13715. * @returns the webGL buffer
  13716. */
  13717. Engine.prototype.createInstancesBuffer = function (capacity) {
  13718. var buffer = this._gl.createBuffer();
  13719. if (!buffer) {
  13720. throw new Error("Unable to create instance buffer");
  13721. }
  13722. buffer.capacity = capacity;
  13723. this.bindArrayBuffer(buffer);
  13724. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13725. return buffer;
  13726. };
  13727. /**
  13728. * Delete a webGL buffer used with instanciation
  13729. * @param buffer defines the webGL buffer to delete
  13730. */
  13731. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13732. this._gl.deleteBuffer(buffer);
  13733. };
  13734. /**
  13735. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13736. * @param instancesBuffer defines the webGL buffer to update and bind
  13737. * @param data defines the data to store in the buffer
  13738. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13739. */
  13740. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13741. this.bindArrayBuffer(instancesBuffer);
  13742. if (data) {
  13743. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13744. }
  13745. if (offsetLocations[0].index !== undefined) {
  13746. var stride = 0;
  13747. for (var i = 0; i < offsetLocations.length; i++) {
  13748. var ai = offsetLocations[i];
  13749. stride += ai.attributeSize * 4;
  13750. }
  13751. for (var i = 0; i < offsetLocations.length; i++) {
  13752. var ai = offsetLocations[i];
  13753. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13754. this._gl.enableVertexAttribArray(ai.index);
  13755. this._vertexAttribArraysEnabled[ai.index] = true;
  13756. }
  13757. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13758. this._gl.vertexAttribDivisor(ai.index, 1);
  13759. this._currentInstanceLocations.push(ai.index);
  13760. this._currentInstanceBuffers.push(instancesBuffer);
  13761. }
  13762. }
  13763. else {
  13764. for (var index = 0; index < 4; index++) {
  13765. var offsetLocation = offsetLocations[index];
  13766. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13767. this._gl.enableVertexAttribArray(offsetLocation);
  13768. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13769. }
  13770. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13771. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13772. this._currentInstanceLocations.push(offsetLocation);
  13773. this._currentInstanceBuffers.push(instancesBuffer);
  13774. }
  13775. }
  13776. };
  13777. /**
  13778. * Apply all cached states (depth, culling, stencil and alpha)
  13779. */
  13780. Engine.prototype.applyStates = function () {
  13781. this._depthCullingState.apply(this._gl);
  13782. this._stencilState.apply(this._gl);
  13783. this._alphaState.apply(this._gl);
  13784. };
  13785. /**
  13786. * Send a draw order
  13787. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13788. * @param indexStart defines the starting index
  13789. * @param indexCount defines the number of index to draw
  13790. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13791. */
  13792. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13793. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13794. };
  13795. /**
  13796. * Draw a list of points
  13797. * @param verticesStart defines the index of first vertex to draw
  13798. * @param verticesCount defines the count of vertices to draw
  13799. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13800. */
  13801. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13802. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13803. };
  13804. /**
  13805. * Draw a list of unindexed primitives
  13806. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13807. * @param verticesStart defines the index of first vertex to draw
  13808. * @param verticesCount defines the count of vertices to draw
  13809. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13810. */
  13811. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13812. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13813. };
  13814. /**
  13815. * Draw a list of indexed primitives
  13816. * @param fillMode defines the primitive to use
  13817. * @param indexStart defines the starting index
  13818. * @param indexCount defines the number of index to draw
  13819. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13820. */
  13821. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13822. // Apply states
  13823. this.applyStates();
  13824. this._drawCalls.addCount(1, false);
  13825. // Render
  13826. var drawMode = this._drawMode(fillMode);
  13827. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13828. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13829. if (instancesCount) {
  13830. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13831. }
  13832. else {
  13833. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13834. }
  13835. };
  13836. /**
  13837. * Draw a list of unindexed primitives
  13838. * @param fillMode defines the primitive to use
  13839. * @param verticesStart defines the index of first vertex to draw
  13840. * @param verticesCount defines the count of vertices to draw
  13841. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13842. */
  13843. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13844. // Apply states
  13845. this.applyStates();
  13846. this._drawCalls.addCount(1, false);
  13847. var drawMode = this._drawMode(fillMode);
  13848. if (instancesCount) {
  13849. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13850. }
  13851. else {
  13852. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13853. }
  13854. };
  13855. Engine.prototype._drawMode = function (fillMode) {
  13856. switch (fillMode) {
  13857. // Triangle views
  13858. case BABYLON.Material.TriangleFillMode:
  13859. return this._gl.TRIANGLES;
  13860. case BABYLON.Material.PointFillMode:
  13861. return this._gl.POINTS;
  13862. case BABYLON.Material.WireFrameFillMode:
  13863. return this._gl.LINES;
  13864. // Draw modes
  13865. case BABYLON.Material.PointListDrawMode:
  13866. return this._gl.POINTS;
  13867. case BABYLON.Material.LineListDrawMode:
  13868. return this._gl.LINES;
  13869. case BABYLON.Material.LineLoopDrawMode:
  13870. return this._gl.LINE_LOOP;
  13871. case BABYLON.Material.LineStripDrawMode:
  13872. return this._gl.LINE_STRIP;
  13873. case BABYLON.Material.TriangleStripDrawMode:
  13874. return this._gl.TRIANGLE_STRIP;
  13875. case BABYLON.Material.TriangleFanDrawMode:
  13876. return this._gl.TRIANGLE_FAN;
  13877. default:
  13878. return this._gl.TRIANGLES;
  13879. }
  13880. };
  13881. // Shaders
  13882. /** @hidden */
  13883. Engine.prototype._releaseEffect = function (effect) {
  13884. if (this._compiledEffects[effect._key]) {
  13885. delete this._compiledEffects[effect._key];
  13886. this._deleteProgram(effect.getProgram());
  13887. }
  13888. };
  13889. /** @hidden */
  13890. Engine.prototype._deleteProgram = function (program) {
  13891. if (program) {
  13892. program.__SPECTOR_rebuildProgram = null;
  13893. if (program.transformFeedback) {
  13894. this.deleteTransformFeedback(program.transformFeedback);
  13895. program.transformFeedback = null;
  13896. }
  13897. this._gl.deleteProgram(program);
  13898. }
  13899. };
  13900. /**
  13901. * Create a new effect (used to store vertex/fragment shaders)
  13902. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13903. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13904. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13905. * @param samplers defines an array of string used to represent textures
  13906. * @param defines defines the string containing the defines to use to compile the shaders
  13907. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13908. * @param onCompiled defines a function to call when the effect creation is successful
  13909. * @param onError defines a function to call when the effect creation has failed
  13910. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13911. * @returns the new Effect
  13912. */
  13913. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13914. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13915. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13916. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13917. if (this._compiledEffects[name]) {
  13918. var compiledEffect = this._compiledEffects[name];
  13919. if (onCompiled && compiledEffect.isReady()) {
  13920. onCompiled(compiledEffect);
  13921. }
  13922. return compiledEffect;
  13923. }
  13924. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13925. effect._key = name;
  13926. this._compiledEffects[name] = effect;
  13927. return effect;
  13928. };
  13929. /**
  13930. * Create an effect to use with particle systems
  13931. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13932. * @param uniformsNames defines a list of attribute names
  13933. * @param samplers defines an array of string used to represent textures
  13934. * @param defines defines the string containing the defines to use to compile the shaders
  13935. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13936. * @param onCompiled defines a function to call when the effect creation is successful
  13937. * @param onError defines a function to call when the effect creation has failed
  13938. * @returns the new Effect
  13939. */
  13940. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13941. if (uniformsNames === void 0) { uniformsNames = []; }
  13942. if (samplers === void 0) { samplers = []; }
  13943. if (defines === void 0) { defines = ""; }
  13944. return this.createEffect({
  13945. vertex: "particles",
  13946. fragmentElement: fragmentName
  13947. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13948. };
  13949. /**
  13950. * Directly creates a webGL program
  13951. * @param vertexCode defines the vertex shader code to use
  13952. * @param fragmentCode defines the fragment shader code to use
  13953. * @param context defines the webGL context to use (if not set, the current one will be used)
  13954. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13955. * @returns the new webGL program
  13956. */
  13957. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13958. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13959. context = context || this._gl;
  13960. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13961. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13962. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13963. };
  13964. /**
  13965. * Creates a webGL program
  13966. * @param vertexCode defines the vertex shader code to use
  13967. * @param fragmentCode defines the fragment shader code to use
  13968. * @param defines defines the string containing the defines to use to compile the shaders
  13969. * @param context defines the webGL context to use (if not set, the current one will be used)
  13970. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13971. * @returns the new webGL program
  13972. */
  13973. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13974. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13975. context = context || this._gl;
  13976. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13977. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13978. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13979. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13980. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13981. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13982. return program;
  13983. };
  13984. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13985. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13986. var shaderProgram = context.createProgram();
  13987. if (!shaderProgram) {
  13988. throw new Error("Unable to create program");
  13989. }
  13990. context.attachShader(shaderProgram, vertexShader);
  13991. context.attachShader(shaderProgram, fragmentShader);
  13992. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13993. var transformFeedback = this.createTransformFeedback();
  13994. this.bindTransformFeedback(transformFeedback);
  13995. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13996. shaderProgram.transformFeedback = transformFeedback;
  13997. }
  13998. context.linkProgram(shaderProgram);
  13999. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14000. this.bindTransformFeedback(null);
  14001. }
  14002. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14003. if (!linked) {
  14004. context.validateProgram(shaderProgram);
  14005. var error = context.getProgramInfoLog(shaderProgram);
  14006. if (error) {
  14007. throw new Error(error);
  14008. }
  14009. }
  14010. context.deleteShader(vertexShader);
  14011. context.deleteShader(fragmentShader);
  14012. return shaderProgram;
  14013. };
  14014. /**
  14015. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14016. * @param shaderProgram defines the webGL program to use
  14017. * @param uniformsNames defines the list of uniform names
  14018. * @returns an array of webGL uniform locations
  14019. */
  14020. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14021. var results = new Array();
  14022. for (var index = 0; index < uniformsNames.length; index++) {
  14023. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14024. }
  14025. return results;
  14026. };
  14027. /**
  14028. * Gets the lsit of active attributes for a given webGL program
  14029. * @param shaderProgram defines the webGL program to use
  14030. * @param attributesNames defines the list of attribute names to get
  14031. * @returns an array of indices indicating the offset of each attribute
  14032. */
  14033. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14034. var results = [];
  14035. for (var index = 0; index < attributesNames.length; index++) {
  14036. try {
  14037. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14038. }
  14039. catch (e) {
  14040. results.push(-1);
  14041. }
  14042. }
  14043. return results;
  14044. };
  14045. /**
  14046. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14047. * @param effect defines the effect to activate
  14048. */
  14049. Engine.prototype.enableEffect = function (effect) {
  14050. if (!effect) {
  14051. return;
  14052. }
  14053. // Use program
  14054. this.bindSamplers(effect);
  14055. this._currentEffect = effect;
  14056. if (effect.onBind) {
  14057. effect.onBind(effect);
  14058. }
  14059. effect.onBindObservable.notifyObservers(effect);
  14060. };
  14061. /**
  14062. * Set the value of an uniform to an array of int32
  14063. * @param uniform defines the webGL uniform location where to store the value
  14064. * @param array defines the array of int32 to store
  14065. */
  14066. Engine.prototype.setIntArray = function (uniform, array) {
  14067. if (!uniform)
  14068. return;
  14069. this._gl.uniform1iv(uniform, array);
  14070. };
  14071. /**
  14072. * Set the value of an uniform to an array of int32 (stored as vec2)
  14073. * @param uniform defines the webGL uniform location where to store the value
  14074. * @param array defines the array of int32 to store
  14075. */
  14076. Engine.prototype.setIntArray2 = function (uniform, array) {
  14077. if (!uniform || array.length % 2 !== 0)
  14078. return;
  14079. this._gl.uniform2iv(uniform, array);
  14080. };
  14081. /**
  14082. * Set the value of an uniform to an array of int32 (stored as vec3)
  14083. * @param uniform defines the webGL uniform location where to store the value
  14084. * @param array defines the array of int32 to store
  14085. */
  14086. Engine.prototype.setIntArray3 = function (uniform, array) {
  14087. if (!uniform || array.length % 3 !== 0)
  14088. return;
  14089. this._gl.uniform3iv(uniform, array);
  14090. };
  14091. /**
  14092. * Set the value of an uniform to an array of int32 (stored as vec4)
  14093. * @param uniform defines the webGL uniform location where to store the value
  14094. * @param array defines the array of int32 to store
  14095. */
  14096. Engine.prototype.setIntArray4 = function (uniform, array) {
  14097. if (!uniform || array.length % 4 !== 0)
  14098. return;
  14099. this._gl.uniform4iv(uniform, array);
  14100. };
  14101. /**
  14102. * Set the value of an uniform to an array of float32
  14103. * @param uniform defines the webGL uniform location where to store the value
  14104. * @param array defines the array of float32 to store
  14105. */
  14106. Engine.prototype.setFloatArray = function (uniform, array) {
  14107. if (!uniform)
  14108. return;
  14109. this._gl.uniform1fv(uniform, array);
  14110. };
  14111. /**
  14112. * Set the value of an uniform to an array of float32 (stored as vec2)
  14113. * @param uniform defines the webGL uniform location where to store the value
  14114. * @param array defines the array of float32 to store
  14115. */
  14116. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14117. if (!uniform || array.length % 2 !== 0)
  14118. return;
  14119. this._gl.uniform2fv(uniform, array);
  14120. };
  14121. /**
  14122. * Set the value of an uniform to an array of float32 (stored as vec3)
  14123. * @param uniform defines the webGL uniform location where to store the value
  14124. * @param array defines the array of float32 to store
  14125. */
  14126. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14127. if (!uniform || array.length % 3 !== 0)
  14128. return;
  14129. this._gl.uniform3fv(uniform, array);
  14130. };
  14131. /**
  14132. * Set the value of an uniform to an array of float32 (stored as vec4)
  14133. * @param uniform defines the webGL uniform location where to store the value
  14134. * @param array defines the array of float32 to store
  14135. */
  14136. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14137. if (!uniform || array.length % 4 !== 0)
  14138. return;
  14139. this._gl.uniform4fv(uniform, array);
  14140. };
  14141. /**
  14142. * Set the value of an uniform to an array of number
  14143. * @param uniform defines the webGL uniform location where to store the value
  14144. * @param array defines the array of number to store
  14145. */
  14146. Engine.prototype.setArray = function (uniform, array) {
  14147. if (!uniform)
  14148. return;
  14149. this._gl.uniform1fv(uniform, array);
  14150. };
  14151. /**
  14152. * Set the value of an uniform to an array of number (stored as vec2)
  14153. * @param uniform defines the webGL uniform location where to store the value
  14154. * @param array defines the array of number to store
  14155. */
  14156. Engine.prototype.setArray2 = function (uniform, array) {
  14157. if (!uniform || array.length % 2 !== 0)
  14158. return;
  14159. this._gl.uniform2fv(uniform, array);
  14160. };
  14161. /**
  14162. * Set the value of an uniform to an array of number (stored as vec3)
  14163. * @param uniform defines the webGL uniform location where to store the value
  14164. * @param array defines the array of number to store
  14165. */
  14166. Engine.prototype.setArray3 = function (uniform, array) {
  14167. if (!uniform || array.length % 3 !== 0)
  14168. return;
  14169. this._gl.uniform3fv(uniform, array);
  14170. };
  14171. /**
  14172. * Set the value of an uniform to an array of number (stored as vec4)
  14173. * @param uniform defines the webGL uniform location where to store the value
  14174. * @param array defines the array of number to store
  14175. */
  14176. Engine.prototype.setArray4 = function (uniform, array) {
  14177. if (!uniform || array.length % 4 !== 0)
  14178. return;
  14179. this._gl.uniform4fv(uniform, array);
  14180. };
  14181. /**
  14182. * Set the value of an uniform to an array of float32 (stored as matrices)
  14183. * @param uniform defines the webGL uniform location where to store the value
  14184. * @param matrices defines the array of float32 to store
  14185. */
  14186. Engine.prototype.setMatrices = function (uniform, matrices) {
  14187. if (!uniform)
  14188. return;
  14189. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14190. };
  14191. /**
  14192. * Set the value of an uniform to a matrix
  14193. * @param uniform defines the webGL uniform location where to store the value
  14194. * @param matrix defines the matrix to store
  14195. */
  14196. Engine.prototype.setMatrix = function (uniform, matrix) {
  14197. if (!uniform)
  14198. return;
  14199. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14200. };
  14201. /**
  14202. * Set the value of an uniform to a matrix (3x3)
  14203. * @param uniform defines the webGL uniform location where to store the value
  14204. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14205. */
  14206. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14207. if (!uniform)
  14208. return;
  14209. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14210. };
  14211. /**
  14212. * Set the value of an uniform to a matrix (2x2)
  14213. * @param uniform defines the webGL uniform location where to store the value
  14214. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14215. */
  14216. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14217. if (!uniform)
  14218. return;
  14219. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14220. };
  14221. /**
  14222. * Set the value of an uniform to a number (int)
  14223. * @param uniform defines the webGL uniform location where to store the value
  14224. * @param value defines the int number to store
  14225. */
  14226. Engine.prototype.setInt = function (uniform, value) {
  14227. if (!uniform)
  14228. return;
  14229. this._gl.uniform1i(uniform, value);
  14230. };
  14231. /**
  14232. * Set the value of an uniform to a number (float)
  14233. * @param uniform defines the webGL uniform location where to store the value
  14234. * @param value defines the float number to store
  14235. */
  14236. Engine.prototype.setFloat = function (uniform, value) {
  14237. if (!uniform)
  14238. return;
  14239. this._gl.uniform1f(uniform, value);
  14240. };
  14241. /**
  14242. * Set the value of an uniform to a vec2
  14243. * @param uniform defines the webGL uniform location where to store the value
  14244. * @param x defines the 1st component of the value
  14245. * @param y defines the 2nd component of the value
  14246. */
  14247. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14248. if (!uniform)
  14249. return;
  14250. this._gl.uniform2f(uniform, x, y);
  14251. };
  14252. /**
  14253. * Set the value of an uniform to a vec3
  14254. * @param uniform defines the webGL uniform location where to store the value
  14255. * @param x defines the 1st component of the value
  14256. * @param y defines the 2nd component of the value
  14257. * @param z defines the 3rd component of the value
  14258. */
  14259. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14260. if (!uniform)
  14261. return;
  14262. this._gl.uniform3f(uniform, x, y, z);
  14263. };
  14264. /**
  14265. * Set the value of an uniform to a boolean
  14266. * @param uniform defines the webGL uniform location where to store the value
  14267. * @param bool defines the boolean to store
  14268. */
  14269. Engine.prototype.setBool = function (uniform, bool) {
  14270. if (!uniform)
  14271. return;
  14272. this._gl.uniform1i(uniform, bool);
  14273. };
  14274. /**
  14275. * Set the value of an uniform to a vec4
  14276. * @param uniform defines the webGL uniform location where to store the value
  14277. * @param x defines the 1st component of the value
  14278. * @param y defines the 2nd component of the value
  14279. * @param z defines the 3rd component of the value
  14280. * @param w defines the 4th component of the value
  14281. */
  14282. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14283. if (!uniform)
  14284. return;
  14285. this._gl.uniform4f(uniform, x, y, z, w);
  14286. };
  14287. /**
  14288. * Set the value of an uniform to a Color3
  14289. * @param uniform defines the webGL uniform location where to store the value
  14290. * @param color3 defines the color to store
  14291. */
  14292. Engine.prototype.setColor3 = function (uniform, color3) {
  14293. if (!uniform)
  14294. return;
  14295. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14296. };
  14297. /**
  14298. * Set the value of an uniform to a Color3 and an alpha value
  14299. * @param uniform defines the webGL uniform location where to store the value
  14300. * @param color3 defines the color to store
  14301. * @param alpha defines the alpha component to store
  14302. */
  14303. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14304. if (!uniform)
  14305. return;
  14306. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14307. };
  14308. /**
  14309. * Sets a Color4 on a uniform variable
  14310. * @param uniform defines the uniform location
  14311. * @param color4 defines the value to be set
  14312. */
  14313. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14314. if (!uniform)
  14315. return;
  14316. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14317. };
  14318. // States
  14319. /**
  14320. * Set various states to the webGL context
  14321. * @param culling defines backface culling state
  14322. * @param zOffset defines the value to apply to zOffset (0 by default)
  14323. * @param force defines if states must be applied even if cache is up to date
  14324. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14325. */
  14326. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14327. if (zOffset === void 0) { zOffset = 0; }
  14328. if (reverseSide === void 0) { reverseSide = false; }
  14329. // Culling
  14330. if (this._depthCullingState.cull !== culling || force) {
  14331. this._depthCullingState.cull = culling;
  14332. }
  14333. // Cull face
  14334. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14335. if (this._depthCullingState.cullFace !== cullFace || force) {
  14336. this._depthCullingState.cullFace = cullFace;
  14337. }
  14338. // Z offset
  14339. this.setZOffset(zOffset);
  14340. // Front face
  14341. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14342. if (this._depthCullingState.frontFace !== frontFace || force) {
  14343. this._depthCullingState.frontFace = frontFace;
  14344. }
  14345. };
  14346. /**
  14347. * Set the z offset to apply to current rendering
  14348. * @param value defines the offset to apply
  14349. */
  14350. Engine.prototype.setZOffset = function (value) {
  14351. this._depthCullingState.zOffset = value;
  14352. };
  14353. /**
  14354. * Gets the current value of the zOffset
  14355. * @returns the current zOffset state
  14356. */
  14357. Engine.prototype.getZOffset = function () {
  14358. return this._depthCullingState.zOffset;
  14359. };
  14360. /**
  14361. * Enable or disable depth buffering
  14362. * @param enable defines the state to set
  14363. */
  14364. Engine.prototype.setDepthBuffer = function (enable) {
  14365. this._depthCullingState.depthTest = enable;
  14366. };
  14367. /**
  14368. * Gets a boolean indicating if depth writing is enabled
  14369. * @returns the current depth writing state
  14370. */
  14371. Engine.prototype.getDepthWrite = function () {
  14372. return this._depthCullingState.depthMask;
  14373. };
  14374. /**
  14375. * Enable or disable depth writing
  14376. * @param enable defines the state to set
  14377. */
  14378. Engine.prototype.setDepthWrite = function (enable) {
  14379. this._depthCullingState.depthMask = enable;
  14380. };
  14381. /**
  14382. * Enable or disable color writing
  14383. * @param enable defines the state to set
  14384. */
  14385. Engine.prototype.setColorWrite = function (enable) {
  14386. this._gl.colorMask(enable, enable, enable, enable);
  14387. this._colorWrite = enable;
  14388. };
  14389. /**
  14390. * Gets a boolean indicating if color writing is enabled
  14391. * @returns the current color writing state
  14392. */
  14393. Engine.prototype.getColorWrite = function () {
  14394. return this._colorWrite;
  14395. };
  14396. /**
  14397. * Sets alpha constants used by some alpha blending modes
  14398. * @param r defines the red component
  14399. * @param g defines the green component
  14400. * @param b defines the blue component
  14401. * @param a defines the alpha component
  14402. */
  14403. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14404. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14405. };
  14406. /**
  14407. * Sets the current alpha mode
  14408. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14409. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14410. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14411. */
  14412. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14413. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14414. if (this._alphaMode === mode) {
  14415. return;
  14416. }
  14417. switch (mode) {
  14418. case Engine.ALPHA_DISABLE:
  14419. this._alphaState.alphaBlend = false;
  14420. break;
  14421. case Engine.ALPHA_PREMULTIPLIED:
  14422. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14423. this._alphaState.alphaBlend = true;
  14424. break;
  14425. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14426. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14427. this._alphaState.alphaBlend = true;
  14428. break;
  14429. case Engine.ALPHA_COMBINE:
  14430. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14431. this._alphaState.alphaBlend = true;
  14432. break;
  14433. case Engine.ALPHA_ONEONE:
  14434. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14435. this._alphaState.alphaBlend = true;
  14436. break;
  14437. case Engine.ALPHA_ADD:
  14438. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14439. this._alphaState.alphaBlend = true;
  14440. break;
  14441. case Engine.ALPHA_SUBTRACT:
  14442. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14443. this._alphaState.alphaBlend = true;
  14444. break;
  14445. case Engine.ALPHA_MULTIPLY:
  14446. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14447. this._alphaState.alphaBlend = true;
  14448. break;
  14449. case Engine.ALPHA_MAXIMIZED:
  14450. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14451. this._alphaState.alphaBlend = true;
  14452. break;
  14453. case Engine.ALPHA_INTERPOLATE:
  14454. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14455. this._alphaState.alphaBlend = true;
  14456. break;
  14457. case Engine.ALPHA_SCREENMODE:
  14458. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14459. this._alphaState.alphaBlend = true;
  14460. break;
  14461. }
  14462. if (!noDepthWriteChange) {
  14463. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14464. }
  14465. this._alphaMode = mode;
  14466. };
  14467. /**
  14468. * Gets the current alpha mode
  14469. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14470. * @returns the current alpha mode
  14471. */
  14472. Engine.prototype.getAlphaMode = function () {
  14473. return this._alphaMode;
  14474. };
  14475. // Textures
  14476. /**
  14477. * Clears the list of texture accessible through engine.
  14478. * This can help preventing texture load conflict due to name collision.
  14479. */
  14480. Engine.prototype.clearInternalTexturesCache = function () {
  14481. this._internalTexturesCache = [];
  14482. };
  14483. /**
  14484. * Force the entire cache to be cleared
  14485. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14486. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14487. */
  14488. Engine.prototype.wipeCaches = function (bruteForce) {
  14489. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14490. return;
  14491. }
  14492. this._currentEffect = null;
  14493. this._unpackFlipYCached = null;
  14494. this._viewportCached.x = 0;
  14495. this._viewportCached.y = 0;
  14496. this._viewportCached.z = 0;
  14497. this._viewportCached.w = 0;
  14498. if (bruteForce) {
  14499. this.resetTextureCache();
  14500. this._currentProgram = null;
  14501. this._stencilState.reset();
  14502. this._depthCullingState.reset();
  14503. this.setDepthFunctionToLessOrEqual();
  14504. this._alphaState.reset();
  14505. }
  14506. this._resetVertexBufferBinding();
  14507. this._cachedIndexBuffer = null;
  14508. this._cachedEffectForVertexBuffers = null;
  14509. this._unbindVertexArrayObject();
  14510. this.bindIndexBuffer(null);
  14511. };
  14512. /**
  14513. * Set the compressed texture format to use, based on the formats you have, and the formats
  14514. * supported by the hardware / browser.
  14515. *
  14516. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14517. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14518. * to API arguments needed to compressed textures. This puts the burden on the container
  14519. * generator to house the arcane code for determining these for current & future formats.
  14520. *
  14521. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14522. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14523. *
  14524. * Note: The result of this call is not taken into account when a texture is base64.
  14525. *
  14526. * @param formatsAvailable defines the list of those format families you have created
  14527. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14528. *
  14529. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14530. * @returns The extension selected.
  14531. */
  14532. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14533. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14534. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14535. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14536. return this._textureFormatInUse = this._texturesSupported[i];
  14537. }
  14538. }
  14539. }
  14540. // actively set format to nothing, to allow this to be called more than once
  14541. // and possibly fail the 2nd time
  14542. this._textureFormatInUse = null;
  14543. return null;
  14544. };
  14545. /** @hidden */
  14546. Engine.prototype._createTexture = function () {
  14547. var texture = this._gl.createTexture();
  14548. if (!texture) {
  14549. throw new Error("Unable to create texture");
  14550. }
  14551. return texture;
  14552. };
  14553. /**
  14554. * Usually called from BABYLON.Texture.ts.
  14555. * Passed information to create a WebGLTexture
  14556. * @param urlArg defines a value which contains one of the following:
  14557. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14558. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14559. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14560. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14561. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14562. * @param scene needed for loading to the correct scene
  14563. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14564. * @param onLoad optional callback to be called upon successful completion
  14565. * @param onError optional callback to be called upon failure
  14566. * @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
  14567. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14568. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14569. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14570. */
  14571. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14572. var _this = this;
  14573. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14574. if (onLoad === void 0) { onLoad = null; }
  14575. if (onError === void 0) { onError = null; }
  14576. if (buffer === void 0) { buffer = null; }
  14577. if (fallback === void 0) { fallback = null; }
  14578. if (format === void 0) { format = null; }
  14579. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14580. var fromData = url.substr(0, 5) === "data:";
  14581. var fromBlob = url.substr(0, 5) === "blob:";
  14582. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14583. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14584. // establish the file extension, if possible
  14585. var lastDot = url.lastIndexOf('.');
  14586. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14587. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14588. var isTGA = (extension.indexOf(".tga") === 0);
  14589. // determine if a ktx file should be substituted
  14590. var isKTX = false;
  14591. if (this._textureFormatInUse && !isBase64 && !fallback && !buffer) {
  14592. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14593. isKTX = true;
  14594. }
  14595. if (scene) {
  14596. scene._addPendingData(texture);
  14597. }
  14598. texture.url = url;
  14599. texture.generateMipMaps = !noMipmap;
  14600. texture.samplingMode = samplingMode;
  14601. texture.invertY = invertY;
  14602. if (!this._doNotHandleContextLost) {
  14603. // Keep a link to the buffer only if we plan to handle context lost
  14604. texture._buffer = buffer;
  14605. }
  14606. var onLoadObserver = null;
  14607. if (onLoad && !fallback) {
  14608. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14609. }
  14610. if (!fallback)
  14611. this._internalTexturesCache.push(texture);
  14612. var onerror = function (message, exception) {
  14613. if (scene) {
  14614. scene._removePendingData(texture);
  14615. }
  14616. if (onLoadObserver && !isKTX) {
  14617. //dont remove the observer if its a ktx file, since the fallback createTexture call will require it.
  14618. texture.onLoadedObservable.remove(onLoadObserver);
  14619. }
  14620. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14621. if (isKTX) {
  14622. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14623. }
  14624. else if (BABYLON.Tools.UseFallbackTexture) {
  14625. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14626. }
  14627. if (onError) {
  14628. onError(message || "Unknown error", exception);
  14629. }
  14630. };
  14631. var callback = null;
  14632. // processing for non-image formats
  14633. if (isKTX || isTGA || isDDS) {
  14634. if (isKTX) {
  14635. callback = function (data) {
  14636. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14637. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14638. ktx.uploadLevels(_this._gl, !noMipmap);
  14639. return false;
  14640. }, samplingMode);
  14641. };
  14642. }
  14643. else if (isTGA) {
  14644. callback = function (arrayBuffer) {
  14645. var data = new Uint8Array(arrayBuffer);
  14646. var header = BABYLON.TGATools.GetTGAHeader(data);
  14647. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14648. BABYLON.TGATools.UploadContent(_this._gl, data);
  14649. return false;
  14650. }, samplingMode);
  14651. };
  14652. }
  14653. else if (isDDS) {
  14654. callback = function (data) {
  14655. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14656. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14657. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14658. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14659. return false;
  14660. }, samplingMode);
  14661. };
  14662. }
  14663. if (!buffer) {
  14664. this._loadFile(url, function (data) {
  14665. if (callback) {
  14666. callback(data);
  14667. }
  14668. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14669. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14670. });
  14671. }
  14672. else {
  14673. if (callback) {
  14674. callback(buffer);
  14675. }
  14676. }
  14677. // image format processing
  14678. }
  14679. else {
  14680. var onload = function (img) {
  14681. if (fromBlob && !_this._doNotHandleContextLost) {
  14682. // We need to store the image if we need to rebuild the texture
  14683. // in case of a webgl context lost
  14684. texture._buffer = img;
  14685. }
  14686. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14687. var gl = _this._gl;
  14688. var isPot = (img.width === potWidth && img.height === potHeight);
  14689. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14690. if (isPot) {
  14691. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14692. return false;
  14693. }
  14694. // Using shaders to rescale because canvas.drawImage is lossy
  14695. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14696. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14697. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14698. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14699. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14700. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14701. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14702. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14703. _this._releaseTexture(source);
  14704. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14705. continuationCallback();
  14706. });
  14707. return true;
  14708. }, samplingMode);
  14709. };
  14710. if (!fromData || isBase64) {
  14711. if (buffer instanceof HTMLImageElement) {
  14712. onload(buffer);
  14713. }
  14714. else {
  14715. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14716. }
  14717. }
  14718. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14719. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14720. }
  14721. else {
  14722. onload(buffer);
  14723. }
  14724. }
  14725. return texture;
  14726. };
  14727. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14728. var _this = this;
  14729. var rtt = this.createRenderTargetTexture({
  14730. width: destination.width,
  14731. height: destination.height,
  14732. }, {
  14733. generateMipMaps: false,
  14734. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14735. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14736. generateDepthBuffer: false,
  14737. generateStencilBuffer: false
  14738. });
  14739. if (!this._rescalePostProcess) {
  14740. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14741. }
  14742. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14743. _this._rescalePostProcess.onApply = function (effect) {
  14744. effect._bindTexture("textureSampler", source);
  14745. };
  14746. var hostingScene = scene;
  14747. if (!hostingScene) {
  14748. hostingScene = _this.scenes[_this.scenes.length - 1];
  14749. }
  14750. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14751. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14752. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14753. _this.unBindFramebuffer(rtt);
  14754. _this._releaseTexture(rtt);
  14755. if (onComplete) {
  14756. onComplete();
  14757. }
  14758. });
  14759. };
  14760. /**
  14761. * Update a raw texture
  14762. * @param texture defines the texture to update
  14763. * @param data defines the data to store in the texture
  14764. * @param format defines the format of the data
  14765. * @param invertY defines if data must be stored with Y axis inverted
  14766. * @param compression defines the compression used (null by default)
  14767. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14768. */
  14769. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14770. if (compression === void 0) { compression = null; }
  14771. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14772. if (!texture) {
  14773. return;
  14774. }
  14775. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14776. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14777. // babylon's internalFormat but gl's texImage2D format
  14778. var internalFormat = this._getInternalFormat(format);
  14779. var textureType = this._getWebGLTextureType(type);
  14780. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14781. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14782. if (!this._doNotHandleContextLost) {
  14783. texture._bufferView = data;
  14784. texture.format = format;
  14785. texture.type = type;
  14786. texture.invertY = invertY;
  14787. texture._compression = compression;
  14788. }
  14789. if (texture.width % 4 !== 0) {
  14790. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14791. }
  14792. if (compression && data) {
  14793. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14794. }
  14795. else {
  14796. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14797. }
  14798. if (texture.generateMipMaps) {
  14799. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14800. }
  14801. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14802. // this.resetTextureCache();
  14803. texture.isReady = true;
  14804. };
  14805. /**
  14806. * Creates a raw texture
  14807. * @param data defines the data to store in the texture
  14808. * @param width defines the width of the texture
  14809. * @param height defines the height of the texture
  14810. * @param format defines the format of the data
  14811. * @param generateMipMaps defines if the engine should generate the mip levels
  14812. * @param invertY defines if data must be stored with Y axis inverted
  14813. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14814. * @param compression defines the compression used (null by default)
  14815. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14816. * @returns the raw texture inside an InternalTexture
  14817. */
  14818. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14819. if (compression === void 0) { compression = null; }
  14820. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14821. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14822. texture.baseWidth = width;
  14823. texture.baseHeight = height;
  14824. texture.width = width;
  14825. texture.height = height;
  14826. texture.format = format;
  14827. texture.generateMipMaps = generateMipMaps;
  14828. texture.samplingMode = samplingMode;
  14829. texture.invertY = invertY;
  14830. texture._compression = compression;
  14831. texture.type = type;
  14832. if (!this._doNotHandleContextLost) {
  14833. texture._bufferView = data;
  14834. }
  14835. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14836. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14837. // Filters
  14838. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14839. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14840. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14841. if (generateMipMaps) {
  14842. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14843. }
  14844. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14845. this._internalTexturesCache.push(texture);
  14846. return texture;
  14847. };
  14848. /** @hidden */
  14849. Engine.prototype._unpackFlipY = function (value) {
  14850. if (this._unpackFlipYCached !== value) {
  14851. this._unpackFlipYCached = value;
  14852. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14853. }
  14854. };
  14855. /**
  14856. * Creates a dynamic texture
  14857. * @param width defines the width of the texture
  14858. * @param height defines the height of the texture
  14859. * @param generateMipMaps defines if the engine should generate the mip levels
  14860. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14861. * @returns the dynamic texture inside an InternalTexture
  14862. */
  14863. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14864. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14865. texture.baseWidth = width;
  14866. texture.baseHeight = height;
  14867. if (generateMipMaps) {
  14868. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14869. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14870. }
  14871. // this.resetTextureCache();
  14872. texture.width = width;
  14873. texture.height = height;
  14874. texture.isReady = false;
  14875. texture.generateMipMaps = generateMipMaps;
  14876. texture.samplingMode = samplingMode;
  14877. this.updateTextureSamplingMode(samplingMode, texture);
  14878. this._internalTexturesCache.push(texture);
  14879. return texture;
  14880. };
  14881. /**
  14882. * Update the sampling mode of a given texture
  14883. * @param samplingMode defines the required sampling mode
  14884. * @param texture defines the texture to update
  14885. */
  14886. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14887. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14888. if (texture.isCube) {
  14889. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14890. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14891. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14892. }
  14893. else if (texture.is3D) {
  14894. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14895. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14896. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14897. }
  14898. else {
  14899. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14900. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14901. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14902. }
  14903. texture.samplingMode = samplingMode;
  14904. };
  14905. /**
  14906. * Update the content of a dynamic texture
  14907. * @param texture defines the texture to update
  14908. * @param canvas defines the canvas containing the source
  14909. * @param invertY defines if data must be stored with Y axis inverted
  14910. * @param premulAlpha defines if alpha is stored as premultiplied
  14911. * @param format defines the format of the data
  14912. */
  14913. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14914. if (premulAlpha === void 0) { premulAlpha = false; }
  14915. if (!texture) {
  14916. return;
  14917. }
  14918. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14919. this._unpackFlipY(invertY);
  14920. if (premulAlpha) {
  14921. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14922. }
  14923. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14924. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14925. if (texture.generateMipMaps) {
  14926. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14927. }
  14928. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14929. if (premulAlpha) {
  14930. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14931. }
  14932. texture.isReady = true;
  14933. };
  14934. /**
  14935. * Update a video texture
  14936. * @param texture defines the texture to update
  14937. * @param video defines the video element to use
  14938. * @param invertY defines if data must be stored with Y axis inverted
  14939. */
  14940. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14941. if (!texture || texture._isDisabled) {
  14942. return;
  14943. }
  14944. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14945. this._unpackFlipY(!invertY); // Video are upside down by default
  14946. try {
  14947. // Testing video texture support
  14948. if (this._videoTextureSupported === undefined) {
  14949. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14950. if (this._gl.getError() !== 0) {
  14951. this._videoTextureSupported = false;
  14952. }
  14953. else {
  14954. this._videoTextureSupported = true;
  14955. }
  14956. }
  14957. // Copy video through the current working canvas if video texture is not supported
  14958. if (!this._videoTextureSupported) {
  14959. if (!texture._workingCanvas) {
  14960. texture._workingCanvas = document.createElement("canvas");
  14961. var context = texture._workingCanvas.getContext("2d");
  14962. if (!context) {
  14963. throw new Error("Unable to get 2d context");
  14964. }
  14965. texture._workingContext = context;
  14966. texture._workingCanvas.width = texture.width;
  14967. texture._workingCanvas.height = texture.height;
  14968. }
  14969. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14970. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14971. }
  14972. else {
  14973. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14974. }
  14975. if (texture.generateMipMaps) {
  14976. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14977. }
  14978. if (!wasPreviouslyBound) {
  14979. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14980. }
  14981. // this.resetTextureCache();
  14982. texture.isReady = true;
  14983. }
  14984. catch (ex) {
  14985. // Something unexpected
  14986. // Let's disable the texture
  14987. texture._isDisabled = true;
  14988. }
  14989. };
  14990. /**
  14991. * Updates a depth texture Comparison Mode and Function.
  14992. * If the comparison Function is equal to 0, the mode will be set to none.
  14993. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14994. * @param texture The texture to set the comparison function for
  14995. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14996. */
  14997. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14998. if (this.webGLVersion === 1) {
  14999. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15000. return;
  15001. }
  15002. var gl = this._gl;
  15003. if (texture.isCube) {
  15004. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15005. if (comparisonFunction === 0) {
  15006. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15007. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15008. }
  15009. else {
  15010. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15011. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15012. }
  15013. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15014. }
  15015. else {
  15016. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15017. if (comparisonFunction === 0) {
  15018. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15019. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15020. }
  15021. else {
  15022. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15023. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15024. }
  15025. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15026. }
  15027. texture._comparisonFunction = comparisonFunction;
  15028. };
  15029. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15030. var width = size.width || size;
  15031. var height = size.height || size;
  15032. internalTexture.baseWidth = width;
  15033. internalTexture.baseHeight = height;
  15034. internalTexture.width = width;
  15035. internalTexture.height = height;
  15036. internalTexture.isReady = true;
  15037. internalTexture.samples = 1;
  15038. internalTexture.generateMipMaps = false;
  15039. internalTexture._generateDepthBuffer = true;
  15040. internalTexture._generateStencilBuffer = generateStencil;
  15041. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15042. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15043. internalTexture._comparisonFunction = comparisonFunction;
  15044. var gl = this._gl;
  15045. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15046. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15047. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15048. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15049. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15050. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15051. if (comparisonFunction === 0) {
  15052. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15053. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15054. }
  15055. else {
  15056. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15057. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15058. }
  15059. };
  15060. /**
  15061. * Creates a depth stencil texture.
  15062. * This is only available in WebGL 2 or with the depth texture extension available.
  15063. * @param size The size of face edge in the texture.
  15064. * @param options The options defining the texture.
  15065. * @returns The texture
  15066. */
  15067. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15068. if (options.isCube) {
  15069. var width = size.width || size;
  15070. return this._createDepthStencilCubeTexture(width, options);
  15071. }
  15072. else {
  15073. return this._createDepthStencilTexture(size, options);
  15074. }
  15075. };
  15076. /**
  15077. * Creates a depth stencil texture.
  15078. * This is only available in WebGL 2 or with the depth texture extension available.
  15079. * @param size The size of face edge in the texture.
  15080. * @param options The options defining the texture.
  15081. * @returns The texture
  15082. */
  15083. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15084. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15085. if (!this._caps.depthTextureExtension) {
  15086. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15087. return internalTexture;
  15088. }
  15089. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15090. var gl = this._gl;
  15091. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15092. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15093. if (this.webGLVersion > 1) {
  15094. if (internalOptions.generateStencil) {
  15095. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15096. }
  15097. else {
  15098. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15099. }
  15100. }
  15101. else {
  15102. if (internalOptions.generateStencil) {
  15103. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15104. }
  15105. else {
  15106. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15107. }
  15108. }
  15109. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15110. return internalTexture;
  15111. };
  15112. /**
  15113. * Creates a depth stencil cube texture.
  15114. * This is only available in WebGL 2.
  15115. * @param size The size of face edge in the cube texture.
  15116. * @param options The options defining the cube texture.
  15117. * @returns The cube texture
  15118. */
  15119. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15120. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15121. internalTexture.isCube = true;
  15122. if (this.webGLVersion === 1) {
  15123. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15124. return internalTexture;
  15125. }
  15126. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15127. var gl = this._gl;
  15128. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15129. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15130. // Create the depth/stencil buffer
  15131. for (var face = 0; face < 6; face++) {
  15132. if (internalOptions.generateStencil) {
  15133. 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);
  15134. }
  15135. else {
  15136. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15137. }
  15138. }
  15139. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15140. return internalTexture;
  15141. };
  15142. /**
  15143. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15144. * @param renderTarget The render target to set the frame buffer for
  15145. */
  15146. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15147. // Create the framebuffer
  15148. var internalTexture = renderTarget.getInternalTexture();
  15149. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15150. return;
  15151. }
  15152. var gl = this._gl;
  15153. var depthStencilTexture = renderTarget.depthStencilTexture;
  15154. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15155. if (depthStencilTexture.isCube) {
  15156. if (depthStencilTexture._generateStencilBuffer) {
  15157. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15158. }
  15159. else {
  15160. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15161. }
  15162. }
  15163. else {
  15164. if (depthStencilTexture._generateStencilBuffer) {
  15165. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15166. }
  15167. else {
  15168. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15169. }
  15170. }
  15171. this.bindUnboundFramebuffer(null);
  15172. };
  15173. /**
  15174. * Creates a new render target texture
  15175. * @param size defines the size of the texture
  15176. * @param options defines the options used to create the texture
  15177. * @returns a new render target texture stored in an InternalTexture
  15178. */
  15179. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15180. var fullOptions = new RenderTargetCreationOptions();
  15181. if (options !== undefined && typeof options === "object") {
  15182. fullOptions.generateMipMaps = options.generateMipMaps;
  15183. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15184. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15185. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15186. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15187. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15188. }
  15189. else {
  15190. fullOptions.generateMipMaps = options;
  15191. fullOptions.generateDepthBuffer = true;
  15192. fullOptions.generateStencilBuffer = false;
  15193. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15194. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15195. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15196. }
  15197. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15198. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15199. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15200. }
  15201. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15202. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15203. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15204. }
  15205. var gl = this._gl;
  15206. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15207. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15208. var width = size.width || size;
  15209. var height = size.height || size;
  15210. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15211. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15212. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15213. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15214. }
  15215. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15216. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15217. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15218. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15219. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15220. // Create the framebuffer
  15221. var currentFrameBuffer = this._currentFramebuffer;
  15222. var framebuffer = gl.createFramebuffer();
  15223. this.bindUnboundFramebuffer(framebuffer);
  15224. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15225. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15226. if (fullOptions.generateMipMaps) {
  15227. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15228. }
  15229. // Unbind
  15230. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15231. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15232. this.bindUnboundFramebuffer(currentFrameBuffer);
  15233. texture._framebuffer = framebuffer;
  15234. texture.baseWidth = width;
  15235. texture.baseHeight = height;
  15236. texture.width = width;
  15237. texture.height = height;
  15238. texture.isReady = true;
  15239. texture.samples = 1;
  15240. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15241. texture.samplingMode = fullOptions.samplingMode;
  15242. texture.type = fullOptions.type;
  15243. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15244. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15245. // this.resetTextureCache();
  15246. this._internalTexturesCache.push(texture);
  15247. return texture;
  15248. };
  15249. /**
  15250. * Create a multi render target texture
  15251. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15252. * @param size defines the size of the texture
  15253. * @param options defines the creation options
  15254. * @returns the cube texture as an InternalTexture
  15255. */
  15256. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15257. var generateMipMaps = false;
  15258. var generateDepthBuffer = true;
  15259. var generateStencilBuffer = false;
  15260. var generateDepthTexture = false;
  15261. var textureCount = 1;
  15262. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15263. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15264. var types = new Array();
  15265. var samplingModes = new Array();
  15266. if (options !== undefined) {
  15267. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15268. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15269. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15270. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15271. textureCount = options.textureCount || 1;
  15272. if (options.types) {
  15273. types = options.types;
  15274. }
  15275. if (options.samplingModes) {
  15276. samplingModes = options.samplingModes;
  15277. }
  15278. }
  15279. var gl = this._gl;
  15280. // Create the framebuffer
  15281. var framebuffer = gl.createFramebuffer();
  15282. this.bindUnboundFramebuffer(framebuffer);
  15283. var width = size.width || size;
  15284. var height = size.height || size;
  15285. var textures = [];
  15286. var attachments = [];
  15287. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15288. for (var i = 0; i < textureCount; i++) {
  15289. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15290. var type = types[i] || defaultType;
  15291. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15292. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15293. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15294. }
  15295. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15296. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15297. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15298. }
  15299. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15300. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15301. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15302. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15303. }
  15304. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15305. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15306. textures.push(texture);
  15307. attachments.push(attachment);
  15308. gl.activeTexture(gl["TEXTURE" + i]);
  15309. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15310. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15311. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15312. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15313. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15314. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15315. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15316. if (generateMipMaps) {
  15317. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15318. }
  15319. // Unbind
  15320. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15321. texture._framebuffer = framebuffer;
  15322. texture._depthStencilBuffer = depthStencilBuffer;
  15323. texture.baseWidth = width;
  15324. texture.baseHeight = height;
  15325. texture.width = width;
  15326. texture.height = height;
  15327. texture.isReady = true;
  15328. texture.samples = 1;
  15329. texture.generateMipMaps = generateMipMaps;
  15330. texture.samplingMode = samplingMode;
  15331. texture.type = type;
  15332. texture._generateDepthBuffer = generateDepthBuffer;
  15333. texture._generateStencilBuffer = generateStencilBuffer;
  15334. texture._attachments = attachments;
  15335. this._internalTexturesCache.push(texture);
  15336. }
  15337. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15338. // Depth texture
  15339. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15340. gl.activeTexture(gl.TEXTURE0);
  15341. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15342. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15343. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15344. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15345. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15346. 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);
  15347. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15348. depthTexture._framebuffer = framebuffer;
  15349. depthTexture.baseWidth = width;
  15350. depthTexture.baseHeight = height;
  15351. depthTexture.width = width;
  15352. depthTexture.height = height;
  15353. depthTexture.isReady = true;
  15354. depthTexture.samples = 1;
  15355. depthTexture.generateMipMaps = generateMipMaps;
  15356. depthTexture.samplingMode = gl.NEAREST;
  15357. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15358. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15359. textures.push(depthTexture);
  15360. this._internalTexturesCache.push(depthTexture);
  15361. }
  15362. gl.drawBuffers(attachments);
  15363. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15364. this.bindUnboundFramebuffer(null);
  15365. this.resetTextureCache();
  15366. return textures;
  15367. };
  15368. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15369. if (samples === void 0) { samples = 1; }
  15370. var depthStencilBuffer = null;
  15371. var gl = this._gl;
  15372. // Create the depth/stencil buffer
  15373. if (generateStencilBuffer) {
  15374. depthStencilBuffer = gl.createRenderbuffer();
  15375. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15376. if (samples > 1) {
  15377. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15378. }
  15379. else {
  15380. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15381. }
  15382. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15383. }
  15384. else if (generateDepthBuffer) {
  15385. depthStencilBuffer = gl.createRenderbuffer();
  15386. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15387. if (samples > 1) {
  15388. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15389. }
  15390. else {
  15391. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15392. }
  15393. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15394. }
  15395. return depthStencilBuffer;
  15396. };
  15397. /**
  15398. * Updates the sample count of a render target texture
  15399. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15400. * @param texture defines the texture to update
  15401. * @param samples defines the sample count to set
  15402. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15403. */
  15404. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15405. if (this.webGLVersion < 2 || !texture) {
  15406. return 1;
  15407. }
  15408. if (texture.samples === samples) {
  15409. return samples;
  15410. }
  15411. var gl = this._gl;
  15412. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15413. // Dispose previous render buffers
  15414. if (texture._depthStencilBuffer) {
  15415. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15416. texture._depthStencilBuffer = null;
  15417. }
  15418. if (texture._MSAAFramebuffer) {
  15419. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15420. texture._MSAAFramebuffer = null;
  15421. }
  15422. if (texture._MSAARenderBuffer) {
  15423. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15424. texture._MSAARenderBuffer = null;
  15425. }
  15426. if (samples > 1) {
  15427. var framebuffer = gl.createFramebuffer();
  15428. if (!framebuffer) {
  15429. throw new Error("Unable to create multi sampled framebuffer");
  15430. }
  15431. texture._MSAAFramebuffer = framebuffer;
  15432. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15433. var colorRenderbuffer = gl.createRenderbuffer();
  15434. if (!colorRenderbuffer) {
  15435. throw new Error("Unable to create multi sampled framebuffer");
  15436. }
  15437. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15438. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15439. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15440. texture._MSAARenderBuffer = colorRenderbuffer;
  15441. }
  15442. else {
  15443. this.bindUnboundFramebuffer(texture._framebuffer);
  15444. }
  15445. texture.samples = samples;
  15446. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15447. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15448. this.bindUnboundFramebuffer(null);
  15449. return samples;
  15450. };
  15451. /**
  15452. * Update the sample count for a given multiple render target texture
  15453. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15454. * @param textures defines the textures to update
  15455. * @param samples defines the sample count to set
  15456. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15457. */
  15458. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15459. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15460. return 1;
  15461. }
  15462. if (textures[0].samples === samples) {
  15463. return samples;
  15464. }
  15465. var gl = this._gl;
  15466. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15467. // Dispose previous render buffers
  15468. if (textures[0]._depthStencilBuffer) {
  15469. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15470. textures[0]._depthStencilBuffer = null;
  15471. }
  15472. if (textures[0]._MSAAFramebuffer) {
  15473. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15474. textures[0]._MSAAFramebuffer = null;
  15475. }
  15476. for (var i = 0; i < textures.length; i++) {
  15477. if (textures[i]._MSAARenderBuffer) {
  15478. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15479. textures[i]._MSAARenderBuffer = null;
  15480. }
  15481. }
  15482. if (samples > 1) {
  15483. var framebuffer = gl.createFramebuffer();
  15484. if (!framebuffer) {
  15485. throw new Error("Unable to create multi sampled framebuffer");
  15486. }
  15487. this.bindUnboundFramebuffer(framebuffer);
  15488. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15489. var attachments = [];
  15490. for (var i = 0; i < textures.length; i++) {
  15491. var texture = textures[i];
  15492. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15493. var colorRenderbuffer = gl.createRenderbuffer();
  15494. if (!colorRenderbuffer) {
  15495. throw new Error("Unable to create multi sampled framebuffer");
  15496. }
  15497. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15498. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15499. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15500. texture._MSAAFramebuffer = framebuffer;
  15501. texture._MSAARenderBuffer = colorRenderbuffer;
  15502. texture.samples = samples;
  15503. texture._depthStencilBuffer = depthStencilBuffer;
  15504. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15505. attachments.push(attachment);
  15506. }
  15507. gl.drawBuffers(attachments);
  15508. }
  15509. else {
  15510. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15511. }
  15512. this.bindUnboundFramebuffer(null);
  15513. return samples;
  15514. };
  15515. /** @hidden */
  15516. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15517. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15518. };
  15519. /** @hidden */
  15520. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15521. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15522. };
  15523. /** @hidden */
  15524. Engine.prototype._uploadImageToTexture = function (texture, faceIndex, lod, image) {
  15525. var gl = this._gl;
  15526. var textureType = this._getWebGLTextureType(texture.type);
  15527. var format = this._getInternalFormat(texture.format);
  15528. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15529. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15530. this._bindTextureDirectly(bindTarget, texture, true);
  15531. this._unpackFlipY(texture.invertY);
  15532. var target = gl.TEXTURE_2D;
  15533. if (texture.isCube) {
  15534. var target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15535. }
  15536. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15537. this._bindTextureDirectly(bindTarget, null, true);
  15538. };
  15539. /**
  15540. * Creates a new render target cube texture
  15541. * @param size defines the size of the texture
  15542. * @param options defines the options used to create the texture
  15543. * @returns a new render target cube texture stored in an InternalTexture
  15544. */
  15545. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15546. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15547. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15548. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15549. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15550. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15551. }
  15552. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15553. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15554. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15555. }
  15556. var gl = this._gl;
  15557. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15558. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15559. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15560. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15561. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15562. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15563. }
  15564. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15565. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15566. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15567. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15568. for (var face = 0; face < 6; face++) {
  15569. 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);
  15570. }
  15571. // Create the framebuffer
  15572. var framebuffer = gl.createFramebuffer();
  15573. this.bindUnboundFramebuffer(framebuffer);
  15574. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15575. // MipMaps
  15576. if (fullOptions.generateMipMaps) {
  15577. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15578. }
  15579. // Unbind
  15580. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15581. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15582. this.bindUnboundFramebuffer(null);
  15583. texture._framebuffer = framebuffer;
  15584. texture.width = size;
  15585. texture.height = size;
  15586. texture.isReady = true;
  15587. texture.isCube = true;
  15588. texture.samples = 1;
  15589. texture.generateMipMaps = fullOptions.generateMipMaps;
  15590. texture.samplingMode = fullOptions.samplingMode;
  15591. texture.type = fullOptions.type;
  15592. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15593. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15594. this._internalTexturesCache.push(texture);
  15595. return texture;
  15596. };
  15597. /**
  15598. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15599. * @param rootUrl defines the url where the file to load is located
  15600. * @param scene defines the current scene
  15601. * @param lodScale defines scale to apply to the mip map selection
  15602. * @param lodOffset defines offset to apply to the mip map selection
  15603. * @param onLoad defines an optional callback raised when the texture is loaded
  15604. * @param onError defines an optional callback raised if there is an issue to load the texture
  15605. * @param format defines the format of the data
  15606. * @param forcedExtension defines the extension to use to pick the right loader
  15607. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15608. * @returns the cube texture as an InternalTexture
  15609. */
  15610. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15611. var _this = this;
  15612. if (onLoad === void 0) { onLoad = null; }
  15613. if (onError === void 0) { onError = null; }
  15614. if (forcedExtension === void 0) { forcedExtension = null; }
  15615. if (createPolynomials === void 0) { createPolynomials = true; }
  15616. var callback = function (loadData) {
  15617. if (!loadData) {
  15618. if (onLoad) {
  15619. onLoad(null);
  15620. }
  15621. return;
  15622. }
  15623. var texture = loadData.texture;
  15624. if (!createPolynomials) {
  15625. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15626. }
  15627. else if (loadData.info.sphericalPolynomial) {
  15628. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15629. }
  15630. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15631. if (_this._caps.textureLOD) {
  15632. // Do not add extra process if texture lod is supported.
  15633. if (onLoad) {
  15634. onLoad(texture);
  15635. }
  15636. return;
  15637. }
  15638. var mipSlices = 3;
  15639. var gl = _this._gl;
  15640. var width = loadData.width;
  15641. if (!width) {
  15642. return;
  15643. }
  15644. var textures = [];
  15645. for (var i = 0; i < mipSlices; i++) {
  15646. //compute LOD from even spacing in smoothness (matching shader calculation)
  15647. var smoothness = i / (mipSlices - 1);
  15648. var roughness = 1 - smoothness;
  15649. var minLODIndex = lodOffset; // roughness = 0
  15650. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15651. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15652. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15653. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15654. glTextureFromLod.isCube = true;
  15655. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15656. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15657. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15658. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15659. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15660. if (loadData.isDDS) {
  15661. var info = loadData.info;
  15662. var data = loadData.data;
  15663. _this._unpackFlipY(info.isCompressed);
  15664. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15665. }
  15666. else {
  15667. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15668. }
  15669. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15670. // Wrap in a base texture for easy binding.
  15671. var lodTexture = new BABYLON.BaseTexture(scene);
  15672. lodTexture.isCube = true;
  15673. lodTexture._texture = glTextureFromLod;
  15674. glTextureFromLod.isReady = true;
  15675. textures.push(lodTexture);
  15676. }
  15677. texture._lodTextureHigh = textures[2];
  15678. texture._lodTextureMid = textures[1];
  15679. texture._lodTextureLow = textures[0];
  15680. if (onLoad) {
  15681. onLoad(texture);
  15682. }
  15683. };
  15684. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15685. };
  15686. /**
  15687. * Creates a cube texture
  15688. * @param rootUrl defines the url where the files to load is located
  15689. * @param scene defines the current scene
  15690. * @param files defines the list of files to load (1 per face)
  15691. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15692. * @param onLoad defines an optional callback raised when the texture is loaded
  15693. * @param onError defines an optional callback raised if there is an issue to load the texture
  15694. * @param format defines the format of the data
  15695. * @param forcedExtension defines the extension to use to pick the right loader
  15696. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15697. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15698. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15699. * @returns the cube texture as an InternalTexture
  15700. */
  15701. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset) {
  15702. var _this = this;
  15703. if (onLoad === void 0) { onLoad = null; }
  15704. if (onError === void 0) { onError = null; }
  15705. if (forcedExtension === void 0) { forcedExtension = null; }
  15706. if (createPolynomials === void 0) { createPolynomials = false; }
  15707. if (lodScale === void 0) { lodScale = 0; }
  15708. if (lodOffset === void 0) { lodOffset = 0; }
  15709. var gl = this._gl;
  15710. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15711. texture.isCube = true;
  15712. texture.url = rootUrl;
  15713. texture.generateMipMaps = !noMipmap;
  15714. texture._lodGenerationScale = lodScale;
  15715. texture._lodGenerationOffset = lodOffset;
  15716. if (!this._doNotHandleContextLost) {
  15717. texture._extension = forcedExtension;
  15718. texture._files = files;
  15719. }
  15720. var isKTX = false;
  15721. var isDDS = false;
  15722. var isEnv = false;
  15723. var lastDot = rootUrl.lastIndexOf('.');
  15724. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15725. if (this._textureFormatInUse) {
  15726. extension = this._textureFormatInUse;
  15727. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15728. isKTX = true;
  15729. }
  15730. else {
  15731. isDDS = (extension === ".dds");
  15732. isEnv = (extension === ".env");
  15733. }
  15734. var onerror = function (request, exception) {
  15735. if (onError && request) {
  15736. onError(request.status + " " + request.statusText, exception);
  15737. }
  15738. };
  15739. if (isKTX) {
  15740. this._loadFile(rootUrl, function (data) {
  15741. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15742. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15743. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15744. _this._unpackFlipY(true);
  15745. ktx.uploadLevels(_this._gl, !noMipmap);
  15746. _this.setCubeMapTextureParams(gl, loadMipmap);
  15747. texture.width = ktx.pixelWidth;
  15748. texture.height = ktx.pixelHeight;
  15749. texture.isReady = true;
  15750. }, undefined, undefined, true, onerror);
  15751. }
  15752. else if (isEnv) {
  15753. this._loadFile(rootUrl, function (data) {
  15754. data = data;
  15755. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  15756. if (info) {
  15757. texture.width = info.width;
  15758. texture.height = info.width;
  15759. BABYLON.EnvironmentTextureTools.UploadPolynomials(texture, data, info);
  15760. BABYLON.EnvironmentTextureTools.UploadLevelsAsync(texture, data, info).then(function () {
  15761. texture.isReady = true;
  15762. if (onLoad) {
  15763. onLoad();
  15764. }
  15765. });
  15766. }
  15767. else if (onError) {
  15768. onError("Can not parse the environment file", null);
  15769. }
  15770. }, undefined, undefined, true, onerror);
  15771. }
  15772. else if (isDDS) {
  15773. if (files && files.length === 6) {
  15774. this._cascadeLoadFiles(scene, function (imgs) {
  15775. var info;
  15776. var loadMipmap = false;
  15777. var width = 0;
  15778. for (var index = 0; index < imgs.length; index++) {
  15779. var data = imgs[index];
  15780. info = BABYLON.DDSTools.GetDDSInfo(data);
  15781. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15782. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15783. _this._unpackFlipY(info.isCompressed);
  15784. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15785. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15786. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15787. }
  15788. texture.width = info.width;
  15789. texture.height = info.height;
  15790. texture.type = info.textureType;
  15791. width = info.width;
  15792. }
  15793. _this.setCubeMapTextureParams(gl, loadMipmap);
  15794. texture.isReady = true;
  15795. if (onLoad) {
  15796. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15797. }
  15798. }, files, onError);
  15799. }
  15800. else {
  15801. this._loadFile(rootUrl, function (data) {
  15802. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15803. if (createPolynomials) {
  15804. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15805. }
  15806. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15807. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15808. _this._unpackFlipY(info.isCompressed);
  15809. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15810. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15811. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15812. }
  15813. _this.setCubeMapTextureParams(gl, loadMipmap);
  15814. texture.width = info.width;
  15815. texture.height = info.height;
  15816. texture.isReady = true;
  15817. texture.type = info.textureType;
  15818. if (onLoad) {
  15819. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15820. }
  15821. }, undefined, undefined, true, onerror);
  15822. }
  15823. }
  15824. else {
  15825. if (!files) {
  15826. throw new Error("Cannot load cubemap because files were not defined");
  15827. }
  15828. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15829. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15830. var height = width;
  15831. _this._prepareWorkingCanvas();
  15832. if (!_this._workingCanvas || !_this._workingContext) {
  15833. return;
  15834. }
  15835. _this._workingCanvas.width = width;
  15836. _this._workingCanvas.height = height;
  15837. var faces = [
  15838. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15839. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15840. ];
  15841. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15842. _this._unpackFlipY(false);
  15843. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15844. for (var index = 0; index < faces.length; index++) {
  15845. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15846. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15847. }
  15848. if (!noMipmap) {
  15849. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15850. }
  15851. _this.setCubeMapTextureParams(gl, !noMipmap);
  15852. texture.width = width;
  15853. texture.height = height;
  15854. texture.isReady = true;
  15855. if (format) {
  15856. texture.format = format;
  15857. }
  15858. texture.onLoadedObservable.notifyObservers(texture);
  15859. texture.onLoadedObservable.clear();
  15860. if (onLoad) {
  15861. onLoad();
  15862. }
  15863. }, files, onError);
  15864. }
  15865. this._internalTexturesCache.push(texture);
  15866. return texture;
  15867. };
  15868. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15869. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15870. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15871. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15872. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15873. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15874. // this.resetTextureCache();
  15875. };
  15876. /**
  15877. * Update a raw cube texture
  15878. * @param texture defines the texture to udpdate
  15879. * @param data defines the data to store
  15880. * @param format defines the data format
  15881. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15882. * @param invertY defines if data must be stored with Y axis inverted
  15883. * @param compression defines the compression used (null by default)
  15884. * @param level defines which level of the texture to update
  15885. */
  15886. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15887. if (compression === void 0) { compression = null; }
  15888. if (level === void 0) { level = 0; }
  15889. texture._bufferViewArray = data;
  15890. texture.format = format;
  15891. texture.type = type;
  15892. texture.invertY = invertY;
  15893. texture._compression = compression;
  15894. var gl = this._gl;
  15895. var textureType = this._getWebGLTextureType(type);
  15896. var internalFormat = this._getInternalFormat(format);
  15897. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15898. var needConversion = false;
  15899. if (internalFormat === gl.RGB) {
  15900. internalFormat = gl.RGBA;
  15901. needConversion = true;
  15902. }
  15903. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15904. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15905. if (texture.width % 4 !== 0) {
  15906. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15907. }
  15908. // Data are known to be in +X +Y +Z -X -Y -Z
  15909. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15910. var faceData = data[faceIndex];
  15911. if (compression) {
  15912. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15913. }
  15914. else {
  15915. if (needConversion) {
  15916. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15917. }
  15918. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15919. }
  15920. }
  15921. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15922. if (isPot && texture.generateMipMaps && level === 0) {
  15923. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15924. }
  15925. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15926. // this.resetTextureCache();
  15927. texture.isReady = true;
  15928. };
  15929. /**
  15930. * Creates a new raw cube texture
  15931. * @param data defines the array of data to use to create each face
  15932. * @param size defines the size of the textures
  15933. * @param format defines the format of the data
  15934. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15935. * @param generateMipMaps defines if the engine should generate the mip levels
  15936. * @param invertY defines if data must be stored with Y axis inverted
  15937. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15938. * @param compression defines the compression used (null by default)
  15939. * @returns the cube texture as an InternalTexture
  15940. */
  15941. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15942. if (compression === void 0) { compression = null; }
  15943. var gl = this._gl;
  15944. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15945. texture.isCube = true;
  15946. texture.generateMipMaps = generateMipMaps;
  15947. texture.format = format;
  15948. texture.type = type;
  15949. if (!this._doNotHandleContextLost) {
  15950. texture._bufferViewArray = data;
  15951. }
  15952. var textureType = this._getWebGLTextureType(type);
  15953. var internalFormat = this._getInternalFormat(format);
  15954. if (internalFormat === gl.RGB) {
  15955. internalFormat = gl.RGBA;
  15956. }
  15957. var width = size;
  15958. var height = width;
  15959. texture.width = width;
  15960. texture.height = height;
  15961. // Double check on POT to generate Mips.
  15962. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15963. if (!isPot) {
  15964. generateMipMaps = false;
  15965. }
  15966. // Upload data if needed. The texture won't be ready until then.
  15967. if (data) {
  15968. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15969. }
  15970. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15971. // Filters
  15972. if (data && generateMipMaps) {
  15973. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15974. }
  15975. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15976. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15977. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15978. }
  15979. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15980. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15981. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15982. }
  15983. else {
  15984. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15985. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15986. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15987. }
  15988. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15989. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15990. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15991. return texture;
  15992. };
  15993. /**
  15994. * Creates a new raw cube texture from a specified url
  15995. * @param url defines the url where the data is located
  15996. * @param scene defines the current scene
  15997. * @param size defines the size of the textures
  15998. * @param format defines the format of the data
  15999. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16000. * @param noMipmap defines if the engine should avoid generating the mip levels
  16001. * @param callback defines a callback used to extract texture data from loaded data
  16002. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16003. * @param onLoad defines a callback called when texture is loaded
  16004. * @param onError defines a callback called if there is an error
  16005. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16006. * @param invertY defines if data must be stored with Y axis inverted
  16007. * @returns the cube texture as an InternalTexture
  16008. */
  16009. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16010. var _this = this;
  16011. if (onLoad === void 0) { onLoad = null; }
  16012. if (onError === void 0) { onError = null; }
  16013. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16014. if (invertY === void 0) { invertY = false; }
  16015. var gl = this._gl;
  16016. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16017. scene._addPendingData(texture);
  16018. texture.url = url;
  16019. this._internalTexturesCache.push(texture);
  16020. var onerror = function (request, exception) {
  16021. scene._removePendingData(texture);
  16022. if (onError && request) {
  16023. onError(request.status + " " + request.statusText, exception);
  16024. }
  16025. };
  16026. var internalCallback = function (data) {
  16027. var width = texture.width;
  16028. var faceDataArrays = callback(data);
  16029. if (!faceDataArrays) {
  16030. return;
  16031. }
  16032. if (mipmapGenerator) {
  16033. var textureType = _this._getWebGLTextureType(type);
  16034. var internalFormat = _this._getInternalFormat(format);
  16035. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16036. var needConversion = false;
  16037. if (internalFormat === gl.RGB) {
  16038. internalFormat = gl.RGBA;
  16039. needConversion = true;
  16040. }
  16041. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16042. _this._unpackFlipY(false);
  16043. var mipData = mipmapGenerator(faceDataArrays);
  16044. for (var level = 0; level < mipData.length; level++) {
  16045. var mipSize = width >> level;
  16046. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16047. var mipFaceData = mipData[level][faceIndex];
  16048. if (needConversion) {
  16049. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16050. }
  16051. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16052. }
  16053. }
  16054. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16055. }
  16056. else {
  16057. texture.generateMipMaps = !noMipmap;
  16058. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16059. }
  16060. texture.isReady = true;
  16061. // this.resetTextureCache();
  16062. scene._removePendingData(texture);
  16063. if (onLoad) {
  16064. onLoad();
  16065. }
  16066. };
  16067. this._loadFile(url, function (data) {
  16068. internalCallback(data);
  16069. }, undefined, scene.database, true, onerror);
  16070. return texture;
  16071. };
  16072. ;
  16073. /**
  16074. * Update a raw 3D texture
  16075. * @param texture defines the texture to update
  16076. * @param data defines the data to store
  16077. * @param format defines the data format
  16078. * @param invertY defines if data must be stored with Y axis inverted
  16079. * @param compression defines the used compression (can be null)
  16080. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16081. */
  16082. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16083. if (compression === void 0) { compression = null; }
  16084. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16085. var internalType = this._getWebGLTextureType(textureType);
  16086. var internalFormat = this._getInternalFormat(format);
  16087. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16088. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16089. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16090. if (!this._doNotHandleContextLost) {
  16091. texture._bufferView = data;
  16092. texture.format = format;
  16093. texture.invertY = invertY;
  16094. texture._compression = compression;
  16095. }
  16096. if (texture.width % 4 !== 0) {
  16097. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16098. }
  16099. if (compression && data) {
  16100. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16101. }
  16102. else {
  16103. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16104. }
  16105. if (texture.generateMipMaps) {
  16106. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16107. }
  16108. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16109. // this.resetTextureCache();
  16110. texture.isReady = true;
  16111. };
  16112. /**
  16113. * Creates a new raw 3D texture
  16114. * @param data defines the data used to create the texture
  16115. * @param width defines the width of the texture
  16116. * @param height defines the height of the texture
  16117. * @param depth defines the depth of the texture
  16118. * @param format defines the format of the texture
  16119. * @param generateMipMaps defines if the engine must generate mip levels
  16120. * @param invertY defines if data must be stored with Y axis inverted
  16121. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16122. * @param compression defines the compressed used (can be null)
  16123. * @param textureType defines the compressed used (can be null)
  16124. * @returns a new raw 3D texture (stored in an InternalTexture)
  16125. */
  16126. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16127. if (compression === void 0) { compression = null; }
  16128. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16129. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16130. texture.baseWidth = width;
  16131. texture.baseHeight = height;
  16132. texture.baseDepth = depth;
  16133. texture.width = width;
  16134. texture.height = height;
  16135. texture.depth = depth;
  16136. texture.format = format;
  16137. texture.type = textureType;
  16138. texture.generateMipMaps = generateMipMaps;
  16139. texture.samplingMode = samplingMode;
  16140. texture.is3D = true;
  16141. if (!this._doNotHandleContextLost) {
  16142. texture._bufferView = data;
  16143. }
  16144. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16145. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16146. // Filters
  16147. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16148. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16149. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16150. if (generateMipMaps) {
  16151. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16152. }
  16153. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16154. this._internalTexturesCache.push(texture);
  16155. return texture;
  16156. };
  16157. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16158. var gl = this._gl;
  16159. if (!gl) {
  16160. return;
  16161. }
  16162. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16163. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16164. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16165. if (!noMipmap && !isCompressed) {
  16166. gl.generateMipmap(gl.TEXTURE_2D);
  16167. }
  16168. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16169. // this.resetTextureCache();
  16170. if (scene) {
  16171. scene._removePendingData(texture);
  16172. }
  16173. texture.onLoadedObservable.notifyObservers(texture);
  16174. texture.onLoadedObservable.clear();
  16175. };
  16176. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16177. var _this = this;
  16178. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16179. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16180. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16181. var gl = this._gl;
  16182. if (!gl) {
  16183. return;
  16184. }
  16185. if (!texture._webGLTexture) {
  16186. // this.resetTextureCache();
  16187. if (scene) {
  16188. scene._removePendingData(texture);
  16189. }
  16190. return;
  16191. }
  16192. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16193. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16194. texture.baseWidth = width;
  16195. texture.baseHeight = height;
  16196. texture.width = potWidth;
  16197. texture.height = potHeight;
  16198. texture.isReady = true;
  16199. if (processFunction(potWidth, potHeight, function () {
  16200. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16201. })) {
  16202. // Returning as texture needs extra async steps
  16203. return;
  16204. }
  16205. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16206. };
  16207. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16208. // Create new RGBA data container.
  16209. var rgbaData;
  16210. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16211. rgbaData = new Float32Array(width * height * 4);
  16212. }
  16213. else {
  16214. rgbaData = new Uint32Array(width * height * 4);
  16215. }
  16216. // Convert each pixel.
  16217. for (var x = 0; x < width; x++) {
  16218. for (var y = 0; y < height; y++) {
  16219. var index = (y * width + x) * 3;
  16220. var newIndex = (y * width + x) * 4;
  16221. // Map Old Value to new value.
  16222. rgbaData[newIndex + 0] = rgbData[index + 0];
  16223. rgbaData[newIndex + 1] = rgbData[index + 1];
  16224. rgbaData[newIndex + 2] = rgbData[index + 2];
  16225. // Add fully opaque alpha channel.
  16226. rgbaData[newIndex + 3] = 1;
  16227. }
  16228. }
  16229. return rgbaData;
  16230. };
  16231. /** @hidden */
  16232. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16233. var gl = this._gl;
  16234. if (texture._framebuffer) {
  16235. gl.deleteFramebuffer(texture._framebuffer);
  16236. texture._framebuffer = null;
  16237. }
  16238. if (texture._depthStencilBuffer) {
  16239. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16240. texture._depthStencilBuffer = null;
  16241. }
  16242. if (texture._MSAAFramebuffer) {
  16243. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16244. texture._MSAAFramebuffer = null;
  16245. }
  16246. if (texture._MSAARenderBuffer) {
  16247. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16248. texture._MSAARenderBuffer = null;
  16249. }
  16250. };
  16251. /** @hidden */
  16252. Engine.prototype._releaseTexture = function (texture) {
  16253. var gl = this._gl;
  16254. this._releaseFramebufferObjects(texture);
  16255. gl.deleteTexture(texture._webGLTexture);
  16256. // Unbind channels
  16257. this.unbindAllTextures();
  16258. var index = this._internalTexturesCache.indexOf(texture);
  16259. if (index !== -1) {
  16260. this._internalTexturesCache.splice(index, 1);
  16261. }
  16262. // Integrated fixed lod samplers.
  16263. if (texture._lodTextureHigh) {
  16264. texture._lodTextureHigh.dispose();
  16265. }
  16266. if (texture._lodTextureMid) {
  16267. texture._lodTextureMid.dispose();
  16268. }
  16269. if (texture._lodTextureLow) {
  16270. texture._lodTextureLow.dispose();
  16271. }
  16272. // Set output texture of post process to null if the texture has been released/disposed
  16273. this.scenes.forEach(function (scene) {
  16274. scene.postProcesses.forEach(function (postProcess) {
  16275. if (postProcess._outputTexture == texture) {
  16276. postProcess._outputTexture = null;
  16277. }
  16278. });
  16279. scene.cameras.forEach(function (camera) {
  16280. camera._postProcesses.forEach(function (postProcess) {
  16281. if (postProcess) {
  16282. if (postProcess._outputTexture == texture) {
  16283. postProcess._outputTexture = null;
  16284. }
  16285. }
  16286. });
  16287. });
  16288. });
  16289. };
  16290. Engine.prototype.setProgram = function (program) {
  16291. if (this._currentProgram !== program) {
  16292. this._gl.useProgram(program);
  16293. this._currentProgram = program;
  16294. }
  16295. };
  16296. /**
  16297. * Binds an effect to the webGL context
  16298. * @param effect defines the effect to bind
  16299. */
  16300. Engine.prototype.bindSamplers = function (effect) {
  16301. this.setProgram(effect.getProgram());
  16302. var samplers = effect.getSamplers();
  16303. for (var index = 0; index < samplers.length; index++) {
  16304. var uniform = effect.getUniform(samplers[index]);
  16305. if (uniform) {
  16306. this._boundUniforms[index] = uniform;
  16307. }
  16308. }
  16309. this._currentEffect = null;
  16310. };
  16311. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16312. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16313. return;
  16314. }
  16315. // Remove
  16316. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16317. // Bind last to it
  16318. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16319. // Bind to dummy
  16320. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16321. };
  16322. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16323. if (!internalTexture) {
  16324. return -1;
  16325. }
  16326. internalTexture._initialSlot = channel;
  16327. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16328. if (channel !== internalTexture._designatedSlot) {
  16329. this._textureCollisions.addCount(1, false);
  16330. }
  16331. }
  16332. else {
  16333. if (channel !== internalTexture._designatedSlot) {
  16334. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16335. return internalTexture._designatedSlot;
  16336. }
  16337. else {
  16338. // No slot for this texture, let's pick a new one (if we find a free slot)
  16339. if (this._nextFreeTextureSlots.length) {
  16340. return this._nextFreeTextureSlots[0];
  16341. }
  16342. // We need to recycle the oldest bound texture, sorry.
  16343. this._textureCollisions.addCount(1, false);
  16344. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16345. }
  16346. }
  16347. }
  16348. return channel;
  16349. };
  16350. Engine.prototype._linkTrackers = function (previous, next) {
  16351. previous.next = next;
  16352. next.previous = previous;
  16353. };
  16354. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16355. var currentSlot = internalTexture._designatedSlot;
  16356. if (currentSlot === -1) {
  16357. return -1;
  16358. }
  16359. internalTexture._designatedSlot = -1;
  16360. if (this.disableTextureBindingOptimization) {
  16361. return -1;
  16362. }
  16363. // Remove from bound list
  16364. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16365. // Free the slot
  16366. this._boundTexturesCache[currentSlot] = null;
  16367. this._nextFreeTextureSlots.push(currentSlot);
  16368. return currentSlot;
  16369. };
  16370. Engine.prototype._activateCurrentTexture = function () {
  16371. if (this._currentTextureChannel !== this._activeChannel) {
  16372. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16373. this._currentTextureChannel = this._activeChannel;
  16374. }
  16375. };
  16376. /** @hidden */
  16377. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16378. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16379. if (force === void 0) { force = false; }
  16380. var wasPreviouslyBound = false;
  16381. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16382. this._activeChannel = texture._designatedSlot;
  16383. }
  16384. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16385. var isTextureForRendering = texture && texture._initialSlot > -1;
  16386. if (currentTextureBound !== texture || force) {
  16387. if (currentTextureBound) {
  16388. this._removeDesignatedSlot(currentTextureBound);
  16389. }
  16390. this._activateCurrentTexture();
  16391. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16392. this._boundTexturesCache[this._activeChannel] = texture;
  16393. if (texture) {
  16394. if (!this.disableTextureBindingOptimization) {
  16395. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16396. if (slotIndex > -1) {
  16397. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16398. }
  16399. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16400. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16401. }
  16402. texture._designatedSlot = this._activeChannel;
  16403. }
  16404. }
  16405. else if (forTextureDataUpdate) {
  16406. wasPreviouslyBound = true;
  16407. this._activateCurrentTexture();
  16408. }
  16409. if (isTextureForRendering && !forTextureDataUpdate) {
  16410. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16411. }
  16412. return wasPreviouslyBound;
  16413. };
  16414. /** @hidden */
  16415. Engine.prototype._bindTexture = function (channel, texture) {
  16416. if (channel < 0) {
  16417. return;
  16418. }
  16419. if (texture) {
  16420. channel = this._getCorrectTextureChannel(channel, texture);
  16421. }
  16422. this._activeChannel = channel;
  16423. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16424. };
  16425. /**
  16426. * Sets a texture to the webGL context from a postprocess
  16427. * @param channel defines the channel to use
  16428. * @param postProcess defines the source postprocess
  16429. */
  16430. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16431. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16432. };
  16433. /**
  16434. * Binds the output of the passed in post process to the texture channel specified
  16435. * @param channel The channel the texture should be bound to
  16436. * @param postProcess The post process which's output should be bound
  16437. */
  16438. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16439. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16440. };
  16441. /**
  16442. * Unbind all textures from the webGL context
  16443. */
  16444. Engine.prototype.unbindAllTextures = function () {
  16445. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16446. this._activeChannel = channel;
  16447. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16448. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16449. if (this.webGLVersion > 1) {
  16450. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16451. }
  16452. }
  16453. };
  16454. /**
  16455. * Sets a texture to the according uniform.
  16456. * @param channel The texture channel
  16457. * @param uniform The uniform to set
  16458. * @param texture The texture to apply
  16459. */
  16460. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16461. if (channel < 0) {
  16462. return;
  16463. }
  16464. if (uniform) {
  16465. this._boundUniforms[channel] = uniform;
  16466. }
  16467. this._setTexture(channel, texture);
  16468. };
  16469. /**
  16470. * Sets a depth stencil texture from a render target to the according uniform.
  16471. * @param channel The texture channel
  16472. * @param uniform The uniform to set
  16473. * @param texture The render target texture containing the depth stencil texture to apply
  16474. */
  16475. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16476. if (channel < 0) {
  16477. return;
  16478. }
  16479. if (uniform) {
  16480. this._boundUniforms[channel] = uniform;
  16481. }
  16482. if (!texture || !texture.depthStencilTexture) {
  16483. this._setTexture(channel, null);
  16484. }
  16485. else {
  16486. this._setTexture(channel, texture, false, true);
  16487. }
  16488. };
  16489. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16490. var uniform = this._boundUniforms[sourceSlot];
  16491. if (uniform._currentState === destination) {
  16492. return;
  16493. }
  16494. this._gl.uniform1i(uniform, destination);
  16495. uniform._currentState = destination;
  16496. };
  16497. Engine.prototype._getTextureWrapMode = function (mode) {
  16498. switch (mode) {
  16499. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16500. return this._gl.REPEAT;
  16501. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16502. return this._gl.CLAMP_TO_EDGE;
  16503. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16504. return this._gl.MIRRORED_REPEAT;
  16505. }
  16506. return this._gl.REPEAT;
  16507. };
  16508. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16509. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16510. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16511. // Not ready?
  16512. if (!texture) {
  16513. if (this._boundTexturesCache[channel] != null) {
  16514. this._activeChannel = channel;
  16515. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16516. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16517. if (this.webGLVersion > 1) {
  16518. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16519. }
  16520. }
  16521. return false;
  16522. }
  16523. // Video
  16524. if (texture.video) {
  16525. this._activeChannel = channel;
  16526. texture.update();
  16527. }
  16528. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16529. texture.delayLoad();
  16530. return false;
  16531. }
  16532. var internalTexture;
  16533. if (depthStencilTexture) {
  16534. internalTexture = texture.depthStencilTexture;
  16535. }
  16536. else if (texture.isReady()) {
  16537. internalTexture = texture.getInternalTexture();
  16538. }
  16539. else if (texture.isCube) {
  16540. internalTexture = this.emptyCubeTexture;
  16541. }
  16542. else if (texture.is3D) {
  16543. internalTexture = this.emptyTexture3D;
  16544. }
  16545. else {
  16546. internalTexture = this.emptyTexture;
  16547. }
  16548. if (!isPartOfTextureArray) {
  16549. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16550. }
  16551. var needToBind = true;
  16552. if (this._boundTexturesCache[channel] === internalTexture) {
  16553. this._moveBoundTextureOnTop(internalTexture);
  16554. if (!isPartOfTextureArray) {
  16555. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16556. }
  16557. needToBind = false;
  16558. }
  16559. this._activeChannel = channel;
  16560. if (internalTexture && internalTexture.is3D) {
  16561. if (needToBind) {
  16562. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16563. }
  16564. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16565. internalTexture._cachedWrapU = texture.wrapU;
  16566. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16567. }
  16568. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16569. internalTexture._cachedWrapV = texture.wrapV;
  16570. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16571. }
  16572. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16573. internalTexture._cachedWrapR = texture.wrapR;
  16574. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16575. }
  16576. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16577. }
  16578. else if (internalTexture && internalTexture.isCube) {
  16579. if (needToBind) {
  16580. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16581. }
  16582. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16583. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16584. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16585. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16586. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16587. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16588. }
  16589. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16590. }
  16591. else {
  16592. if (needToBind) {
  16593. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16594. }
  16595. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16596. internalTexture._cachedWrapU = texture.wrapU;
  16597. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16598. }
  16599. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16600. internalTexture._cachedWrapV = texture.wrapV;
  16601. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16602. }
  16603. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16604. }
  16605. return true;
  16606. };
  16607. /**
  16608. * Sets an array of texture to the webGL context
  16609. * @param channel defines the channel where the texture array must be set
  16610. * @param uniform defines the associated uniform location
  16611. * @param textures defines the array of textures to bind
  16612. */
  16613. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16614. if (channel < 0 || !uniform) {
  16615. return;
  16616. }
  16617. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16618. this._textureUnits = new Int32Array(textures.length);
  16619. }
  16620. for (var i = 0; i < textures.length; i++) {
  16621. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16622. }
  16623. this._gl.uniform1iv(uniform, this._textureUnits);
  16624. for (var index = 0; index < textures.length; index++) {
  16625. this._setTexture(this._textureUnits[index], textures[index], true);
  16626. }
  16627. };
  16628. /** @hidden */
  16629. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16630. var internalTexture = texture.getInternalTexture();
  16631. if (!internalTexture) {
  16632. return;
  16633. }
  16634. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16635. var value = texture.anisotropicFilteringLevel;
  16636. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16637. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16638. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16639. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16640. }
  16641. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16642. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16643. internalTexture._cachedAnisotropicFilteringLevel = value;
  16644. }
  16645. };
  16646. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16647. this._bindTextureDirectly(target, texture, true, true);
  16648. this._gl.texParameterf(target, parameter, value);
  16649. };
  16650. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16651. if (texture) {
  16652. this._bindTextureDirectly(target, texture, true, true);
  16653. }
  16654. this._gl.texParameteri(target, parameter, value);
  16655. };
  16656. /**
  16657. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16658. * @param x defines the x coordinate of the rectangle where pixels must be read
  16659. * @param y defines the y coordinate of the rectangle where pixels must be read
  16660. * @param width defines the width of the rectangle where pixels must be read
  16661. * @param height defines the height of the rectangle where pixels must be read
  16662. * @returns a Uint8Array containing RGBA colors
  16663. */
  16664. Engine.prototype.readPixels = function (x, y, width, height) {
  16665. var data = new Uint8Array(height * width * 4);
  16666. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16667. return data;
  16668. };
  16669. /**
  16670. * Add an externaly attached data from its key.
  16671. * This method call will fail and return false, if such key already exists.
  16672. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16673. * @param key the unique key that identifies the data
  16674. * @param data the data object to associate to the key for this Engine instance
  16675. * @return true if no such key were already present and the data was added successfully, false otherwise
  16676. */
  16677. Engine.prototype.addExternalData = function (key, data) {
  16678. if (!this._externalData) {
  16679. this._externalData = new BABYLON.StringDictionary();
  16680. }
  16681. return this._externalData.add(key, data);
  16682. };
  16683. /**
  16684. * Get an externaly attached data from its key
  16685. * @param key the unique key that identifies the data
  16686. * @return the associated data, if present (can be null), or undefined if not present
  16687. */
  16688. Engine.prototype.getExternalData = function (key) {
  16689. if (!this._externalData) {
  16690. this._externalData = new BABYLON.StringDictionary();
  16691. }
  16692. return this._externalData.get(key);
  16693. };
  16694. /**
  16695. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16696. * @param key the unique key that identifies the data
  16697. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16698. * @return the associated data, can be null if the factory returned null.
  16699. */
  16700. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16701. if (!this._externalData) {
  16702. this._externalData = new BABYLON.StringDictionary();
  16703. }
  16704. return this._externalData.getOrAddWithFactory(key, factory);
  16705. };
  16706. /**
  16707. * Remove an externaly attached data from the Engine instance
  16708. * @param key the unique key that identifies the data
  16709. * @return true if the data was successfully removed, false if it doesn't exist
  16710. */
  16711. Engine.prototype.removeExternalData = function (key) {
  16712. if (!this._externalData) {
  16713. this._externalData = new BABYLON.StringDictionary();
  16714. }
  16715. return this._externalData.remove(key);
  16716. };
  16717. /**
  16718. * Unbind all vertex attributes from the webGL context
  16719. */
  16720. Engine.prototype.unbindAllAttributes = function () {
  16721. if (this._mustWipeVertexAttributes) {
  16722. this._mustWipeVertexAttributes = false;
  16723. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16724. this._gl.disableVertexAttribArray(i);
  16725. this._vertexAttribArraysEnabled[i] = false;
  16726. this._currentBufferPointers[i].active = false;
  16727. }
  16728. return;
  16729. }
  16730. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16731. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16732. continue;
  16733. }
  16734. this._gl.disableVertexAttribArray(i);
  16735. this._vertexAttribArraysEnabled[i] = false;
  16736. this._currentBufferPointers[i].active = false;
  16737. }
  16738. };
  16739. /**
  16740. * 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
  16741. */
  16742. Engine.prototype.releaseEffects = function () {
  16743. for (var name in this._compiledEffects) {
  16744. this._deleteProgram(this._compiledEffects[name]._program);
  16745. }
  16746. this._compiledEffects = {};
  16747. };
  16748. /**
  16749. * Dispose and release all associated resources
  16750. */
  16751. Engine.prototype.dispose = function () {
  16752. this.hideLoadingUI();
  16753. this.stopRenderLoop();
  16754. // Release postProcesses
  16755. while (this.postProcesses.length) {
  16756. this.postProcesses[0].dispose();
  16757. }
  16758. // Empty texture
  16759. if (this._emptyTexture) {
  16760. this._releaseTexture(this._emptyTexture);
  16761. this._emptyTexture = null;
  16762. }
  16763. if (this._emptyCubeTexture) {
  16764. this._releaseTexture(this._emptyCubeTexture);
  16765. this._emptyCubeTexture = null;
  16766. }
  16767. // Rescale PP
  16768. if (this._rescalePostProcess) {
  16769. this._rescalePostProcess.dispose();
  16770. }
  16771. // Release scenes
  16772. while (this.scenes.length) {
  16773. this.scenes[0].dispose();
  16774. }
  16775. // Release audio engine
  16776. if (Engine.audioEngine) {
  16777. Engine.audioEngine.dispose();
  16778. }
  16779. // Release effects
  16780. this.releaseEffects();
  16781. // Unbind
  16782. this.unbindAllAttributes();
  16783. this._boundUniforms = [];
  16784. if (this._dummyFramebuffer) {
  16785. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16786. }
  16787. //WebVR
  16788. this.disableVR();
  16789. // Events
  16790. if (BABYLON.Tools.IsWindowObjectExist()) {
  16791. window.removeEventListener("blur", this._onBlur);
  16792. window.removeEventListener("focus", this._onFocus);
  16793. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16794. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16795. if (this._renderingCanvas) {
  16796. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16797. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16798. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16799. if (!this._doNotHandleContextLost) {
  16800. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16801. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16802. }
  16803. }
  16804. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16805. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16806. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16807. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16808. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16809. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16810. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16811. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16812. if (this._onVrDisplayConnect) {
  16813. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16814. if (this._onVrDisplayDisconnect) {
  16815. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16816. }
  16817. if (this._onVrDisplayPresentChange) {
  16818. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16819. }
  16820. this._onVrDisplayConnect = null;
  16821. this._onVrDisplayDisconnect = null;
  16822. }
  16823. }
  16824. // Remove from Instances
  16825. var index = Engine.Instances.indexOf(this);
  16826. if (index >= 0) {
  16827. Engine.Instances.splice(index, 1);
  16828. }
  16829. this._workingCanvas = null;
  16830. this._workingContext = null;
  16831. this._currentBufferPointers = [];
  16832. this._renderingCanvas = null;
  16833. this._currentProgram = null;
  16834. this._bindedRenderFunction = null;
  16835. this.onResizeObservable.clear();
  16836. this.onCanvasBlurObservable.clear();
  16837. this.onCanvasFocusObservable.clear();
  16838. this.onCanvasPointerOutObservable.clear();
  16839. this.onBeginFrameObservable.clear();
  16840. this.onEndFrameObservable.clear();
  16841. BABYLON.Effect.ResetCache();
  16842. // Abort active requests
  16843. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16844. var request = _a[_i];
  16845. request.abort();
  16846. }
  16847. };
  16848. // Loading screen
  16849. /**
  16850. * Display the loading screen
  16851. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16852. */
  16853. Engine.prototype.displayLoadingUI = function () {
  16854. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16855. return;
  16856. }
  16857. var loadingScreen = this.loadingScreen;
  16858. if (loadingScreen) {
  16859. loadingScreen.displayLoadingUI();
  16860. }
  16861. };
  16862. /**
  16863. * Hide the loading screen
  16864. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16865. */
  16866. Engine.prototype.hideLoadingUI = function () {
  16867. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16868. return;
  16869. }
  16870. var loadingScreen = this.loadingScreen;
  16871. if (loadingScreen) {
  16872. loadingScreen.hideLoadingUI();
  16873. }
  16874. };
  16875. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16876. /**
  16877. * Gets the current loading screen object
  16878. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16879. */
  16880. get: function () {
  16881. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16882. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16883. return this._loadingScreen;
  16884. },
  16885. /**
  16886. * Sets the current loading screen object
  16887. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16888. */
  16889. set: function (loadingScreen) {
  16890. this._loadingScreen = loadingScreen;
  16891. },
  16892. enumerable: true,
  16893. configurable: true
  16894. });
  16895. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16896. /**
  16897. * Sets the current loading screen text
  16898. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16899. */
  16900. set: function (text) {
  16901. this.loadingScreen.loadingUIText = text;
  16902. },
  16903. enumerable: true,
  16904. configurable: true
  16905. });
  16906. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16907. /**
  16908. * Sets the current loading screen background color
  16909. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16910. */
  16911. set: function (color) {
  16912. this.loadingScreen.loadingUIBackgroundColor = color;
  16913. },
  16914. enumerable: true,
  16915. configurable: true
  16916. });
  16917. /**
  16918. * Attach a new callback raised when context lost event is fired
  16919. * @param callback defines the callback to call
  16920. */
  16921. Engine.prototype.attachContextLostEvent = function (callback) {
  16922. if (this._renderingCanvas) {
  16923. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16924. }
  16925. };
  16926. /**
  16927. * Attach a new callback raised when context restored event is fired
  16928. * @param callback defines the callback to call
  16929. */
  16930. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16931. if (this._renderingCanvas) {
  16932. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16933. }
  16934. };
  16935. /**
  16936. * Gets the source code of the vertex shader associated with a specific webGL program
  16937. * @param program defines the program to use
  16938. * @returns a string containing the source code of the vertex shader associated with the program
  16939. */
  16940. Engine.prototype.getVertexShaderSource = function (program) {
  16941. var shaders = this._gl.getAttachedShaders(program);
  16942. if (!shaders) {
  16943. return null;
  16944. }
  16945. return this._gl.getShaderSource(shaders[0]);
  16946. };
  16947. /**
  16948. * Gets the source code of the fragment shader associated with a specific webGL program
  16949. * @param program defines the program to use
  16950. * @returns a string containing the source code of the fragment shader associated with the program
  16951. */
  16952. Engine.prototype.getFragmentShaderSource = function (program) {
  16953. var shaders = this._gl.getAttachedShaders(program);
  16954. if (!shaders) {
  16955. return null;
  16956. }
  16957. return this._gl.getShaderSource(shaders[1]);
  16958. };
  16959. /**
  16960. * Get the current error code of the webGL context
  16961. * @returns the error code
  16962. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16963. */
  16964. Engine.prototype.getError = function () {
  16965. return this._gl.getError();
  16966. };
  16967. // FPS
  16968. /**
  16969. * Gets the current framerate
  16970. * @returns a number representing the framerate
  16971. */
  16972. Engine.prototype.getFps = function () {
  16973. return this._fps;
  16974. };
  16975. /**
  16976. * Gets the time spent between current and previous frame
  16977. * @returns a number representing the delta time in ms
  16978. */
  16979. Engine.prototype.getDeltaTime = function () {
  16980. return this._deltaTime;
  16981. };
  16982. Engine.prototype._measureFps = function () {
  16983. this._performanceMonitor.sampleFrame();
  16984. this._fps = this._performanceMonitor.averageFPS;
  16985. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16986. };
  16987. /** @hidden */
  16988. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16989. if (faceIndex === void 0) { faceIndex = -1; }
  16990. if (level === void 0) { level = 0; }
  16991. var gl = this._gl;
  16992. if (!this._dummyFramebuffer) {
  16993. var dummy = gl.createFramebuffer();
  16994. if (!dummy) {
  16995. throw new Error("Unable to create dummy framebuffer");
  16996. }
  16997. this._dummyFramebuffer = dummy;
  16998. }
  16999. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17000. if (faceIndex > -1) {
  17001. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17002. }
  17003. else {
  17004. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17005. }
  17006. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17007. var buffer;
  17008. switch (readType) {
  17009. case gl.UNSIGNED_BYTE:
  17010. buffer = new Uint8Array(4 * width * height);
  17011. readType = gl.UNSIGNED_BYTE;
  17012. break;
  17013. default:
  17014. buffer = new Float32Array(4 * width * height);
  17015. readType = gl.FLOAT;
  17016. break;
  17017. }
  17018. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17019. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17020. return buffer;
  17021. };
  17022. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17023. if (this._webGLVersion > 1) {
  17024. return this._caps.colorBufferFloat;
  17025. }
  17026. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17027. };
  17028. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17029. if (this._webGLVersion > 1) {
  17030. return this._caps.colorBufferFloat;
  17031. }
  17032. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17033. };
  17034. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17035. Engine.prototype._canRenderToFramebuffer = function (type) {
  17036. var gl = this._gl;
  17037. //clear existing errors
  17038. while (gl.getError() !== gl.NO_ERROR) { }
  17039. var successful = true;
  17040. var texture = gl.createTexture();
  17041. gl.bindTexture(gl.TEXTURE_2D, texture);
  17042. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17043. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17044. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17045. var fb = gl.createFramebuffer();
  17046. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17047. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17048. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17049. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17050. successful = successful && (gl.getError() === gl.NO_ERROR);
  17051. //try render by clearing frame buffer's color buffer
  17052. if (successful) {
  17053. gl.clear(gl.COLOR_BUFFER_BIT);
  17054. successful = successful && (gl.getError() === gl.NO_ERROR);
  17055. }
  17056. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17057. if (successful) {
  17058. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17059. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17060. var readFormat = gl.RGBA;
  17061. var readType = gl.UNSIGNED_BYTE;
  17062. var buffer = new Uint8Array(4);
  17063. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17064. successful = successful && (gl.getError() === gl.NO_ERROR);
  17065. }
  17066. //clean up
  17067. gl.deleteTexture(texture);
  17068. gl.deleteFramebuffer(fb);
  17069. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17070. //clear accumulated errors
  17071. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17072. return successful;
  17073. };
  17074. /** @hidden */
  17075. Engine.prototype._getWebGLTextureType = function (type) {
  17076. if (type === Engine.TEXTURETYPE_FLOAT) {
  17077. return this._gl.FLOAT;
  17078. }
  17079. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17080. // Add Half Float Constant.
  17081. return this._gl.HALF_FLOAT_OES;
  17082. }
  17083. return this._gl.UNSIGNED_BYTE;
  17084. };
  17085. ;
  17086. Engine.prototype._getInternalFormat = function (format) {
  17087. var internalFormat = this._gl.RGBA;
  17088. switch (format) {
  17089. case Engine.TEXTUREFORMAT_ALPHA:
  17090. internalFormat = this._gl.ALPHA;
  17091. break;
  17092. case Engine.TEXTUREFORMAT_LUMINANCE:
  17093. internalFormat = this._gl.LUMINANCE;
  17094. break;
  17095. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17096. internalFormat = this._gl.LUMINANCE_ALPHA;
  17097. break;
  17098. case Engine.TEXTUREFORMAT_RGB:
  17099. internalFormat = this._gl.RGB;
  17100. break;
  17101. case Engine.TEXTUREFORMAT_RGBA:
  17102. internalFormat = this._gl.RGBA;
  17103. break;
  17104. case Engine.TEXTUREFORMAT_R:
  17105. internalFormat = this._gl.RED;
  17106. break;
  17107. case Engine.TEXTUREFORMAT_RG:
  17108. internalFormat = this._gl.RG;
  17109. break;
  17110. }
  17111. return internalFormat;
  17112. };
  17113. /** @hidden */
  17114. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17115. if (this._webGLVersion === 1) {
  17116. if (format !== undefined) {
  17117. switch (format) {
  17118. case Engine.TEXTUREFORMAT_LUMINANCE:
  17119. return this._gl.LUMINANCE;
  17120. case Engine.TEXTUREFORMAT_ALPHA:
  17121. return this._gl.ALPHA;
  17122. }
  17123. }
  17124. return this._gl.RGBA;
  17125. }
  17126. if (type === Engine.TEXTURETYPE_FLOAT) {
  17127. if (format !== undefined) {
  17128. switch (format) {
  17129. case Engine.TEXTUREFORMAT_R:
  17130. return this._gl.R32F;
  17131. case Engine.TEXTUREFORMAT_RG:
  17132. return this._gl.RG32F;
  17133. case Engine.TEXTUREFORMAT_RGB:
  17134. return this._gl.RGB32F;
  17135. }
  17136. }
  17137. return this._gl.RGBA32F;
  17138. }
  17139. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17140. if (format) {
  17141. switch (format) {
  17142. case Engine.TEXTUREFORMAT_R:
  17143. return this._gl.R16F;
  17144. case Engine.TEXTUREFORMAT_RG:
  17145. return this._gl.RG16F;
  17146. case Engine.TEXTUREFORMAT_RGB:
  17147. return this._gl.RGB16F;
  17148. }
  17149. }
  17150. return this._gl.RGBA16F;
  17151. }
  17152. if (format !== undefined) {
  17153. switch (format) {
  17154. case Engine.TEXTUREFORMAT_LUMINANCE:
  17155. return this._gl.LUMINANCE;
  17156. case Engine.TEXTUREFORMAT_RGB:
  17157. return this._gl.RGB;
  17158. case Engine.TEXTUREFORMAT_R:
  17159. return this._gl.R8;
  17160. case Engine.TEXTUREFORMAT_RG:
  17161. return this._gl.RG8;
  17162. case Engine.TEXTUREFORMAT_ALPHA:
  17163. return this._gl.ALPHA;
  17164. }
  17165. }
  17166. return this._gl.RGBA;
  17167. };
  17168. ;
  17169. /** @hidden */
  17170. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17171. if (type === Engine.TEXTURETYPE_FLOAT) {
  17172. return this._gl.RGBA32F;
  17173. }
  17174. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17175. return this._gl.RGBA16F;
  17176. }
  17177. return this._gl.RGBA8;
  17178. };
  17179. ;
  17180. /**
  17181. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17182. * @return the new query
  17183. */
  17184. Engine.prototype.createQuery = function () {
  17185. return this._gl.createQuery();
  17186. };
  17187. /**
  17188. * Delete and release a webGL query
  17189. * @param query defines the query to delete
  17190. * @return the current engine
  17191. */
  17192. Engine.prototype.deleteQuery = function (query) {
  17193. this._gl.deleteQuery(query);
  17194. return this;
  17195. };
  17196. /**
  17197. * Check if a given query has resolved and got its value
  17198. * @param query defines the query to check
  17199. * @returns true if the query got its value
  17200. */
  17201. Engine.prototype.isQueryResultAvailable = function (query) {
  17202. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17203. };
  17204. /**
  17205. * Gets the value of a given query
  17206. * @param query defines the query to check
  17207. * @returns the value of the query
  17208. */
  17209. Engine.prototype.getQueryResult = function (query) {
  17210. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17211. };
  17212. /**
  17213. * Initiates an occlusion query
  17214. * @param algorithmType defines the algorithm to use
  17215. * @param query defines the query to use
  17216. * @returns the current engine
  17217. * @see http://doc.babylonjs.com/features/occlusionquery
  17218. */
  17219. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17220. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17221. this._gl.beginQuery(glAlgorithm, query);
  17222. return this;
  17223. };
  17224. /**
  17225. * Ends an occlusion query
  17226. * @see http://doc.babylonjs.com/features/occlusionquery
  17227. * @param algorithmType defines the algorithm to use
  17228. * @returns the current engine
  17229. */
  17230. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17231. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17232. this._gl.endQuery(glAlgorithm);
  17233. return this;
  17234. };
  17235. /* Time queries */
  17236. Engine.prototype._createTimeQuery = function () {
  17237. var timerQuery = this._caps.timerQuery;
  17238. if (timerQuery.createQueryEXT) {
  17239. return timerQuery.createQueryEXT();
  17240. }
  17241. return this.createQuery();
  17242. };
  17243. Engine.prototype._deleteTimeQuery = function (query) {
  17244. var timerQuery = this._caps.timerQuery;
  17245. if (timerQuery.deleteQueryEXT) {
  17246. timerQuery.deleteQueryEXT(query);
  17247. return;
  17248. }
  17249. this.deleteQuery(query);
  17250. };
  17251. Engine.prototype._getTimeQueryResult = function (query) {
  17252. var timerQuery = this._caps.timerQuery;
  17253. if (timerQuery.getQueryObjectEXT) {
  17254. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17255. }
  17256. return this.getQueryResult(query);
  17257. };
  17258. Engine.prototype._getTimeQueryAvailability = function (query) {
  17259. var timerQuery = this._caps.timerQuery;
  17260. if (timerQuery.getQueryObjectEXT) {
  17261. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17262. }
  17263. return this.isQueryResultAvailable(query);
  17264. };
  17265. /**
  17266. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17267. * Please note that only one query can be issued at a time
  17268. * @returns a time token used to track the time span
  17269. */
  17270. Engine.prototype.startTimeQuery = function () {
  17271. var timerQuery = this._caps.timerQuery;
  17272. if (!timerQuery) {
  17273. return null;
  17274. }
  17275. var token = new BABYLON._TimeToken();
  17276. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17277. if (this._caps.canUseTimestampForTimerQuery) {
  17278. token._startTimeQuery = this._createTimeQuery();
  17279. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17280. }
  17281. else {
  17282. if (this._currentNonTimestampToken) {
  17283. return this._currentNonTimestampToken;
  17284. }
  17285. token._timeElapsedQuery = this._createTimeQuery();
  17286. if (timerQuery.beginQueryEXT) {
  17287. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17288. }
  17289. else {
  17290. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17291. }
  17292. this._currentNonTimestampToken = token;
  17293. }
  17294. return token;
  17295. };
  17296. /**
  17297. * Ends a time query
  17298. * @param token defines the token used to measure the time span
  17299. * @returns the time spent (in ns)
  17300. */
  17301. Engine.prototype.endTimeQuery = function (token) {
  17302. var timerQuery = this._caps.timerQuery;
  17303. if (!timerQuery || !token) {
  17304. return -1;
  17305. }
  17306. if (this._caps.canUseTimestampForTimerQuery) {
  17307. if (!token._startTimeQuery) {
  17308. return -1;
  17309. }
  17310. if (!token._endTimeQuery) {
  17311. token._endTimeQuery = this._createTimeQuery();
  17312. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17313. }
  17314. }
  17315. else if (!token._timeElapsedQueryEnded) {
  17316. if (!token._timeElapsedQuery) {
  17317. return -1;
  17318. }
  17319. if (timerQuery.endQueryEXT) {
  17320. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17321. }
  17322. else {
  17323. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17324. }
  17325. token._timeElapsedQueryEnded = true;
  17326. }
  17327. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17328. var available = false;
  17329. if (token._endTimeQuery) {
  17330. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17331. }
  17332. else if (token._timeElapsedQuery) {
  17333. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17334. }
  17335. if (available && !disjoint) {
  17336. var result = 0;
  17337. if (this._caps.canUseTimestampForTimerQuery) {
  17338. if (!token._startTimeQuery || !token._endTimeQuery) {
  17339. return -1;
  17340. }
  17341. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17342. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17343. result = timeEnd - timeStart;
  17344. this._deleteTimeQuery(token._startTimeQuery);
  17345. this._deleteTimeQuery(token._endTimeQuery);
  17346. token._startTimeQuery = null;
  17347. token._endTimeQuery = null;
  17348. }
  17349. else {
  17350. if (!token._timeElapsedQuery) {
  17351. return -1;
  17352. }
  17353. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17354. this._deleteTimeQuery(token._timeElapsedQuery);
  17355. token._timeElapsedQuery = null;
  17356. token._timeElapsedQueryEnded = false;
  17357. this._currentNonTimestampToken = null;
  17358. }
  17359. return result;
  17360. }
  17361. return -1;
  17362. };
  17363. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17364. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17365. };
  17366. // Transform feedback
  17367. /**
  17368. * Creates a webGL transform feedback object
  17369. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17370. * @returns the webGL transform feedback object
  17371. */
  17372. Engine.prototype.createTransformFeedback = function () {
  17373. return this._gl.createTransformFeedback();
  17374. };
  17375. /**
  17376. * Delete a webGL transform feedback object
  17377. * @param value defines the webGL transform feedback object to delete
  17378. */
  17379. Engine.prototype.deleteTransformFeedback = function (value) {
  17380. this._gl.deleteTransformFeedback(value);
  17381. };
  17382. /**
  17383. * Bind a webGL transform feedback object to the webgl context
  17384. * @param value defines the webGL transform feedback object to bind
  17385. */
  17386. Engine.prototype.bindTransformFeedback = function (value) {
  17387. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17388. };
  17389. /**
  17390. * Begins a transform feedback operation
  17391. * @param usePoints defines if points or triangles must be used
  17392. */
  17393. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17394. if (usePoints === void 0) { usePoints = true; }
  17395. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17396. };
  17397. /**
  17398. * Ends a transform feedback operation
  17399. */
  17400. Engine.prototype.endTransformFeedback = function () {
  17401. this._gl.endTransformFeedback();
  17402. };
  17403. /**
  17404. * Specify the varyings to use with transform feedback
  17405. * @param program defines the associated webGL program
  17406. * @param value defines the list of strings representing the varying names
  17407. */
  17408. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17409. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17410. };
  17411. /**
  17412. * Bind a webGL buffer for a transform feedback operation
  17413. * @param value defines the webGL buffer to bind
  17414. */
  17415. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17416. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17417. };
  17418. /** @hidden */
  17419. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17420. var _this = this;
  17421. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17422. this._activeRequests.push(request);
  17423. request.onCompleteObservable.add(function (request) {
  17424. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17425. });
  17426. return request;
  17427. };
  17428. /** @hidden */
  17429. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17430. var _this = this;
  17431. return new Promise(function (resolve, reject) {
  17432. _this._loadFile(url, function (data) {
  17433. resolve(data);
  17434. }, undefined, database, useArrayBuffer, function (request, exception) {
  17435. reject(exception);
  17436. });
  17437. });
  17438. };
  17439. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17440. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17441. var onload = function (data) {
  17442. loadedFiles[index] = data;
  17443. loadedFiles._internalCount++;
  17444. if (loadedFiles._internalCount === 6) {
  17445. onfinish(loadedFiles);
  17446. }
  17447. };
  17448. var onerror = function (request, exception) {
  17449. if (onErrorCallBack && request) {
  17450. onErrorCallBack(request.status + " " + request.statusText, exception);
  17451. }
  17452. };
  17453. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17454. };
  17455. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17456. if (onError === void 0) { onError = null; }
  17457. var loadedFiles = [];
  17458. loadedFiles._internalCount = 0;
  17459. for (var index = 0; index < 6; index++) {
  17460. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17461. }
  17462. };
  17463. // Statics
  17464. /**
  17465. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17466. * @returns true if the engine can be created
  17467. * @ignorenaming
  17468. */
  17469. Engine.isSupported = function () {
  17470. try {
  17471. var tempcanvas = document.createElement("canvas");
  17472. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17473. return gl != null && !!window.WebGLRenderingContext;
  17474. }
  17475. catch (e) {
  17476. return false;
  17477. }
  17478. };
  17479. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17480. Engine.ExceptionList = [
  17481. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17482. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17483. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17484. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17485. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17486. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17487. ];
  17488. /** Gets the list of created engines */
  17489. Engine.Instances = new Array();
  17490. // Const statics
  17491. Engine._ALPHA_DISABLE = 0;
  17492. Engine._ALPHA_ADD = 1;
  17493. Engine._ALPHA_COMBINE = 2;
  17494. Engine._ALPHA_SUBTRACT = 3;
  17495. Engine._ALPHA_MULTIPLY = 4;
  17496. Engine._ALPHA_MAXIMIZED = 5;
  17497. Engine._ALPHA_ONEONE = 6;
  17498. Engine._ALPHA_PREMULTIPLIED = 7;
  17499. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17500. Engine._ALPHA_INTERPOLATE = 9;
  17501. Engine._ALPHA_SCREENMODE = 10;
  17502. Engine._DELAYLOADSTATE_NONE = 0;
  17503. Engine._DELAYLOADSTATE_LOADED = 1;
  17504. Engine._DELAYLOADSTATE_LOADING = 2;
  17505. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17506. Engine._TEXTUREFORMAT_ALPHA = 0;
  17507. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17508. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17509. Engine._TEXTUREFORMAT_RGB = 4;
  17510. Engine._TEXTUREFORMAT_RGBA = 5;
  17511. Engine._TEXTUREFORMAT_R = 6;
  17512. Engine._TEXTUREFORMAT_RG = 7;
  17513. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17514. Engine._TEXTURETYPE_FLOAT = 1;
  17515. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17516. // Depht or Stencil test Constants.
  17517. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17518. Engine._ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
  17519. Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  17520. Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  17521. Engine._LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
  17522. Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  17523. Engine._GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
  17524. Engine._NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
  17525. // Stencil Actions Constants.
  17526. Engine._KEEP = 0x1E00;
  17527. Engine._REPLACE = 0x1E01;
  17528. Engine._INCR = 0x1E02;
  17529. Engine._DECR = 0x1E03;
  17530. Engine._INVERT = 0x150A;
  17531. Engine._INCR_WRAP = 0x8507;
  17532. Engine._DECR_WRAP = 0x8508;
  17533. // Texture rescaling mode
  17534. Engine._SCALEMODE_FLOOR = 1;
  17535. Engine._SCALEMODE_NEAREST = 2;
  17536. Engine._SCALEMODE_CEILING = 3;
  17537. // Updatable statics so stick with vars here
  17538. /**
  17539. * Gets or sets the epsilon value used by collision engine
  17540. */
  17541. Engine.CollisionsEpsilon = 0.001;
  17542. /**
  17543. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17544. */
  17545. Engine.CodeRepository = "src/";
  17546. /**
  17547. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17548. */
  17549. Engine.ShadersRepository = "src/Shaders/";
  17550. return Engine;
  17551. }());
  17552. BABYLON.Engine = Engine;
  17553. })(BABYLON || (BABYLON = {}));
  17554. //# sourceMappingURL=babylon.engine.js.map
  17555. var BABYLON;
  17556. (function (BABYLON) {
  17557. /**
  17558. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17559. */
  17560. var Node = /** @class */ (function () {
  17561. /**
  17562. * Creates a new Node
  17563. * @param {string} name - the name and id to be given to this node
  17564. * @param {BABYLON.Scene} the scene this node will be added to
  17565. */
  17566. function Node(name, scene) {
  17567. if (scene === void 0) { scene = null; }
  17568. /**
  17569. * Gets or sets a string used to store user defined state for the node
  17570. */
  17571. this.state = "";
  17572. /**
  17573. * Gets or sets an object used to store user defined information for the node
  17574. */
  17575. this.metadata = null;
  17576. /**
  17577. * Gets or sets a boolean used to define if the node must be serialized
  17578. */
  17579. this.doNotSerialize = false;
  17580. /** @hidden */
  17581. this._isDisposed = false;
  17582. /**
  17583. * Gets a list of Animations associated with the node
  17584. */
  17585. this.animations = new Array();
  17586. this._ranges = {};
  17587. this._isEnabled = true;
  17588. this._isReady = true;
  17589. /** @hidden */
  17590. this._currentRenderId = -1;
  17591. this._parentRenderId = -1;
  17592. this._childRenderId = -1;
  17593. this._animationPropertiesOverride = null;
  17594. /**
  17595. * An event triggered when the mesh is disposed
  17596. */
  17597. this.onDisposeObservable = new BABYLON.Observable();
  17598. // Behaviors
  17599. this._behaviors = new Array();
  17600. this.name = name;
  17601. this.id = name;
  17602. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17603. this.uniqueId = this._scene.getUniqueId();
  17604. this._initCache();
  17605. }
  17606. /**
  17607. * Gets a boolean indicating if the node has been disposed
  17608. * @returns true if the node was disposed
  17609. */
  17610. Node.prototype.isDisposed = function () {
  17611. return this._isDisposed;
  17612. };
  17613. Object.defineProperty(Node.prototype, "parent", {
  17614. get: function () {
  17615. return this._parentNode;
  17616. },
  17617. /**
  17618. * Gets or sets the parent of the node
  17619. */
  17620. set: function (parent) {
  17621. if (this._parentNode === parent) {
  17622. return;
  17623. }
  17624. // Remove self from list of children of parent
  17625. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17626. var index = this._parentNode._children.indexOf(this);
  17627. if (index !== -1) {
  17628. this._parentNode._children.splice(index, 1);
  17629. }
  17630. }
  17631. // Store new parent
  17632. this._parentNode = parent;
  17633. // Add as child to new parent
  17634. if (this._parentNode) {
  17635. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17636. this._parentNode._children = new Array();
  17637. }
  17638. this._parentNode._children.push(this);
  17639. }
  17640. },
  17641. enumerable: true,
  17642. configurable: true
  17643. });
  17644. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17645. /**
  17646. * Gets or sets the animation properties override
  17647. */
  17648. get: function () {
  17649. if (!this._animationPropertiesOverride) {
  17650. return this._scene.animationPropertiesOverride;
  17651. }
  17652. return this._animationPropertiesOverride;
  17653. },
  17654. set: function (value) {
  17655. this._animationPropertiesOverride = value;
  17656. },
  17657. enumerable: true,
  17658. configurable: true
  17659. });
  17660. /**
  17661. * Gets a string idenfifying the name of the class
  17662. * @returns "Node" string
  17663. */
  17664. Node.prototype.getClassName = function () {
  17665. return "Node";
  17666. };
  17667. Object.defineProperty(Node.prototype, "onDispose", {
  17668. /**
  17669. * Sets a callback that will be raised when the node will be disposed
  17670. */
  17671. set: function (callback) {
  17672. if (this._onDisposeObserver) {
  17673. this.onDisposeObservable.remove(this._onDisposeObserver);
  17674. }
  17675. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17676. },
  17677. enumerable: true,
  17678. configurable: true
  17679. });
  17680. /**
  17681. * Gets the scene of the node
  17682. * @returns a {BABYLON.Scene}
  17683. */
  17684. Node.prototype.getScene = function () {
  17685. return this._scene;
  17686. };
  17687. /**
  17688. * Gets the engine of the node
  17689. * @returns a {BABYLON.Engine}
  17690. */
  17691. Node.prototype.getEngine = function () {
  17692. return this._scene.getEngine();
  17693. };
  17694. /**
  17695. * Attach a behavior to the node
  17696. * @see http://doc.babylonjs.com/features/behaviour
  17697. * @param behavior defines the behavior to attach
  17698. * @returns the current Node
  17699. */
  17700. Node.prototype.addBehavior = function (behavior) {
  17701. var _this = this;
  17702. var index = this._behaviors.indexOf(behavior);
  17703. if (index !== -1) {
  17704. return this;
  17705. }
  17706. behavior.init();
  17707. if (this._scene.isLoading) {
  17708. // We defer the attach when the scene will be loaded
  17709. this._scene.onDataLoadedObservable.addOnce(function () {
  17710. behavior.attach(_this);
  17711. });
  17712. }
  17713. else {
  17714. behavior.attach(this);
  17715. }
  17716. this._behaviors.push(behavior);
  17717. return this;
  17718. };
  17719. /**
  17720. * Remove an attached behavior
  17721. * @see http://doc.babylonjs.com/features/behaviour
  17722. * @param behavior defines the behavior to attach
  17723. * @returns the current Node
  17724. */
  17725. Node.prototype.removeBehavior = function (behavior) {
  17726. var index = this._behaviors.indexOf(behavior);
  17727. if (index === -1) {
  17728. return this;
  17729. }
  17730. this._behaviors[index].detach();
  17731. this._behaviors.splice(index, 1);
  17732. return this;
  17733. };
  17734. Object.defineProperty(Node.prototype, "behaviors", {
  17735. /**
  17736. * Gets the list of attached behaviors
  17737. * @see http://doc.babylonjs.com/features/behaviour
  17738. */
  17739. get: function () {
  17740. return this._behaviors;
  17741. },
  17742. enumerable: true,
  17743. configurable: true
  17744. });
  17745. /**
  17746. * Gets an attached behavior by name
  17747. * @param name defines the name of the behavior to look for
  17748. * @see http://doc.babylonjs.com/features/behaviour
  17749. * @returns null if behavior was not found else the requested behavior
  17750. */
  17751. Node.prototype.getBehaviorByName = function (name) {
  17752. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17753. var behavior = _a[_i];
  17754. if (behavior.name === name) {
  17755. return behavior;
  17756. }
  17757. }
  17758. return null;
  17759. };
  17760. /**
  17761. * Returns the world matrix of the node
  17762. * @returns a matrix containing the node's world matrix
  17763. */
  17764. Node.prototype.getWorldMatrix = function () {
  17765. return BABYLON.Matrix.Identity();
  17766. };
  17767. /** @hidden */
  17768. Node.prototype._getWorldMatrixDeterminant = function () {
  17769. return 1;
  17770. };
  17771. // override it in derived class if you add new variables to the cache
  17772. // and call the parent class method
  17773. /** @hidden */
  17774. Node.prototype._initCache = function () {
  17775. this._cache = {};
  17776. this._cache.parent = undefined;
  17777. };
  17778. /** @hidden */
  17779. Node.prototype.updateCache = function (force) {
  17780. if (!force && this.isSynchronized())
  17781. return;
  17782. this._cache.parent = this.parent;
  17783. this._updateCache();
  17784. };
  17785. // override it in derived class if you add new variables to the cache
  17786. // and call the parent class method if !ignoreParentClass
  17787. /** @hidden */
  17788. Node.prototype._updateCache = function (ignoreParentClass) {
  17789. };
  17790. // override it in derived class if you add new variables to the cache
  17791. /** @hidden */
  17792. Node.prototype._isSynchronized = function () {
  17793. return true;
  17794. };
  17795. /** @hidden */
  17796. Node.prototype._markSyncedWithParent = function () {
  17797. if (this.parent) {
  17798. this._parentRenderId = this.parent._childRenderId;
  17799. }
  17800. };
  17801. /** @hidden */
  17802. Node.prototype.isSynchronizedWithParent = function () {
  17803. if (!this.parent) {
  17804. return true;
  17805. }
  17806. if (this._parentRenderId !== this.parent._childRenderId) {
  17807. return false;
  17808. }
  17809. return this.parent.isSynchronized();
  17810. };
  17811. /** @hidden */
  17812. Node.prototype.isSynchronized = function (updateCache) {
  17813. var check = this.hasNewParent();
  17814. check = check || !this.isSynchronizedWithParent();
  17815. check = check || !this._isSynchronized();
  17816. if (updateCache)
  17817. this.updateCache(true);
  17818. return !check;
  17819. };
  17820. /** @hidden */
  17821. Node.prototype.hasNewParent = function (update) {
  17822. if (this._cache.parent === this.parent)
  17823. return false;
  17824. if (update)
  17825. this._cache.parent = this.parent;
  17826. return true;
  17827. };
  17828. /**
  17829. * Is this node ready to be used/rendered
  17830. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17831. * @return true if the node is ready
  17832. */
  17833. Node.prototype.isReady = function (completeCheck) {
  17834. if (completeCheck === void 0) { completeCheck = false; }
  17835. return this._isReady;
  17836. };
  17837. /**
  17838. * Is this node enabled?
  17839. * 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
  17840. * @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
  17841. * @return whether this node (and its parent) is enabled
  17842. */
  17843. Node.prototype.isEnabled = function (checkAncestors) {
  17844. if (checkAncestors === void 0) { checkAncestors = true; }
  17845. if (checkAncestors === false) {
  17846. return this._isEnabled;
  17847. }
  17848. if (this._isEnabled === false) {
  17849. return false;
  17850. }
  17851. if (this.parent !== undefined && this.parent !== null) {
  17852. return this.parent.isEnabled(checkAncestors);
  17853. }
  17854. return true;
  17855. };
  17856. /**
  17857. * Set the enabled state of this node
  17858. * @param value defines the new enabled state
  17859. */
  17860. Node.prototype.setEnabled = function (value) {
  17861. this._isEnabled = value;
  17862. };
  17863. /**
  17864. * Is this node a descendant of the given node?
  17865. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17866. * @param ancestor defines the parent node to inspect
  17867. * @returns a boolean indicating if this node is a descendant of the given node
  17868. */
  17869. Node.prototype.isDescendantOf = function (ancestor) {
  17870. if (this.parent) {
  17871. if (this.parent === ancestor) {
  17872. return true;
  17873. }
  17874. return this.parent.isDescendantOf(ancestor);
  17875. }
  17876. return false;
  17877. };
  17878. /** @hidden */
  17879. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17880. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17881. if (!this._children) {
  17882. return;
  17883. }
  17884. for (var index = 0; index < this._children.length; index++) {
  17885. var item = this._children[index];
  17886. if (!predicate || predicate(item)) {
  17887. results.push(item);
  17888. }
  17889. if (!directDescendantsOnly) {
  17890. item._getDescendants(results, false, predicate);
  17891. }
  17892. }
  17893. };
  17894. /**
  17895. * Will return all nodes that have this node as ascendant
  17896. * @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
  17897. * @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
  17898. * @return all children nodes of all types
  17899. */
  17900. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17901. var results = new Array();
  17902. this._getDescendants(results, directDescendantsOnly, predicate);
  17903. return results;
  17904. };
  17905. /**
  17906. * Get all child-meshes of this node
  17907. * @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
  17908. * @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
  17909. * @returns an array of {BABYLON.AbstractMesh}
  17910. */
  17911. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17912. var results = [];
  17913. this._getDescendants(results, directDescendantsOnly, function (node) {
  17914. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17915. });
  17916. return results;
  17917. };
  17918. /**
  17919. * Get all child-transformNodes of this node
  17920. * @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
  17921. * @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
  17922. * @returns an array of {BABYLON.TransformNode}
  17923. */
  17924. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17925. var results = [];
  17926. this._getDescendants(results, directDescendantsOnly, function (node) {
  17927. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17928. });
  17929. return results;
  17930. };
  17931. /**
  17932. * Get all direct children of this node
  17933. * @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
  17934. * @returns an array of {BABYLON.Node}
  17935. */
  17936. Node.prototype.getChildren = function (predicate) {
  17937. return this.getDescendants(true, predicate);
  17938. };
  17939. /** @hidden */
  17940. Node.prototype._setReady = function (state) {
  17941. if (state === this._isReady) {
  17942. return;
  17943. }
  17944. if (!state) {
  17945. this._isReady = false;
  17946. return;
  17947. }
  17948. if (this.onReady) {
  17949. this.onReady(this);
  17950. }
  17951. this._isReady = true;
  17952. };
  17953. /**
  17954. * Get an animation by name
  17955. * @param name defines the name of the animation to look for
  17956. * @returns null if not found else the requested animation
  17957. */
  17958. Node.prototype.getAnimationByName = function (name) {
  17959. for (var i = 0; i < this.animations.length; i++) {
  17960. var animation = this.animations[i];
  17961. if (animation.name === name) {
  17962. return animation;
  17963. }
  17964. }
  17965. return null;
  17966. };
  17967. /**
  17968. * Creates an animation range for this node
  17969. * @param name defines the name of the range
  17970. * @param from defines the starting key
  17971. * @param to defines the end key
  17972. */
  17973. Node.prototype.createAnimationRange = function (name, from, to) {
  17974. // check name not already in use
  17975. if (!this._ranges[name]) {
  17976. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17977. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17978. if (this.animations[i]) {
  17979. this.animations[i].createRange(name, from, to);
  17980. }
  17981. }
  17982. }
  17983. };
  17984. /**
  17985. * Delete a specific animation range
  17986. * @param name defines the name of the range to delete
  17987. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17988. */
  17989. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17990. if (deleteFrames === void 0) { deleteFrames = true; }
  17991. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17992. if (this.animations[i]) {
  17993. this.animations[i].deleteRange(name, deleteFrames);
  17994. }
  17995. }
  17996. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17997. };
  17998. /**
  17999. * Get an animation range by name
  18000. * @param name defines the name of the animation range to look for
  18001. * @returns null if not found else the requested animation range
  18002. */
  18003. Node.prototype.getAnimationRange = function (name) {
  18004. return this._ranges[name];
  18005. };
  18006. /**
  18007. * Will start the animation sequence
  18008. * @param name defines the range frames for animation sequence
  18009. * @param loop defines if the animation should loop (false by default)
  18010. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18011. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18012. * @returns the object created for this animation. If range does not exist, it will return null
  18013. */
  18014. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18015. var range = this.getAnimationRange(name);
  18016. if (!range) {
  18017. return null;
  18018. }
  18019. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18020. };
  18021. /**
  18022. * Serialize animation ranges into a JSON compatible object
  18023. * @returns serialization object
  18024. */
  18025. Node.prototype.serializeAnimationRanges = function () {
  18026. var serializationRanges = [];
  18027. for (var name in this._ranges) {
  18028. var localRange = this._ranges[name];
  18029. if (!localRange) {
  18030. continue;
  18031. }
  18032. var range = {};
  18033. range.name = name;
  18034. range.from = localRange.from;
  18035. range.to = localRange.to;
  18036. serializationRanges.push(range);
  18037. }
  18038. return serializationRanges;
  18039. };
  18040. /**
  18041. * Computes the world matrix of the node
  18042. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18043. * @returns the world matrix
  18044. */
  18045. Node.prototype.computeWorldMatrix = function (force) {
  18046. return BABYLON.Matrix.Identity();
  18047. };
  18048. /**
  18049. * Releases resources associated with this node.
  18050. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18051. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18052. */
  18053. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18054. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18055. if (!doNotRecurse) {
  18056. var nodes = this.getDescendants(true);
  18057. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18058. var node = nodes_1[_i];
  18059. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18060. }
  18061. }
  18062. else {
  18063. var transformNodes = this.getChildTransformNodes(true);
  18064. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18065. var transformNode = transformNodes_1[_a];
  18066. transformNode.parent = null;
  18067. transformNode.computeWorldMatrix(true);
  18068. }
  18069. }
  18070. this.parent = null;
  18071. // Callback
  18072. this.onDisposeObservable.notifyObservers(this);
  18073. this.onDisposeObservable.clear();
  18074. // Behaviors
  18075. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18076. var behavior = _c[_b];
  18077. behavior.detach();
  18078. }
  18079. this._behaviors = [];
  18080. this._isDisposed = true;
  18081. };
  18082. /**
  18083. * Parse animation range data from a serialization object and store them into a given node
  18084. * @param node defines where to store the animation ranges
  18085. * @param parsedNode defines the serialization object to read data from
  18086. * @param scene defines the hosting scene
  18087. */
  18088. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18089. if (parsedNode.ranges) {
  18090. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18091. var data = parsedNode.ranges[index];
  18092. node.createAnimationRange(data.name, data.from, data.to);
  18093. }
  18094. }
  18095. };
  18096. __decorate([
  18097. BABYLON.serialize()
  18098. ], Node.prototype, "name", void 0);
  18099. __decorate([
  18100. BABYLON.serialize()
  18101. ], Node.prototype, "id", void 0);
  18102. __decorate([
  18103. BABYLON.serialize()
  18104. ], Node.prototype, "uniqueId", void 0);
  18105. __decorate([
  18106. BABYLON.serialize()
  18107. ], Node.prototype, "state", void 0);
  18108. __decorate([
  18109. BABYLON.serialize()
  18110. ], Node.prototype, "metadata", void 0);
  18111. return Node;
  18112. }());
  18113. BABYLON.Node = Node;
  18114. })(BABYLON || (BABYLON = {}));
  18115. //# sourceMappingURL=babylon.node.js.map
  18116. var BABYLON;
  18117. (function (BABYLON) {
  18118. var BoundingSphere = /** @class */ (function () {
  18119. /**
  18120. * Creates a new bounding sphere
  18121. * @param min defines the minimum vector (in local space)
  18122. * @param max defines the maximum vector (in local space)
  18123. */
  18124. function BoundingSphere(min, max) {
  18125. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18126. this.reConstruct(min, max);
  18127. }
  18128. /**
  18129. * Recreates the entire bounding sphere from scratch
  18130. * @param min defines the new minimum vector (in local space)
  18131. * @param max defines the new maximum vector (in local space)
  18132. */
  18133. BoundingSphere.prototype.reConstruct = function (min, max) {
  18134. this.minimum = min.clone();
  18135. this.maximum = max.clone();
  18136. var distance = BABYLON.Vector3.Distance(min, max);
  18137. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18138. this.radius = distance * 0.5;
  18139. this.centerWorld = BABYLON.Vector3.Zero();
  18140. this._update(BABYLON.Matrix.Identity());
  18141. };
  18142. // Methods
  18143. BoundingSphere.prototype._update = function (world) {
  18144. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18145. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18146. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18147. };
  18148. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18149. for (var i = 0; i < 6; i++) {
  18150. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18151. return false;
  18152. }
  18153. return true;
  18154. };
  18155. BoundingSphere.prototype.intersectsPoint = function (point) {
  18156. var x = this.centerWorld.x - point.x;
  18157. var y = this.centerWorld.y - point.y;
  18158. var z = this.centerWorld.z - point.z;
  18159. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18160. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18161. return false;
  18162. return true;
  18163. };
  18164. // Statics
  18165. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18166. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18167. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18168. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18169. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18170. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18171. return false;
  18172. return true;
  18173. };
  18174. return BoundingSphere;
  18175. }());
  18176. BABYLON.BoundingSphere = BoundingSphere;
  18177. })(BABYLON || (BABYLON = {}));
  18178. //# sourceMappingURL=babylon.boundingSphere.js.map
  18179. var BABYLON;
  18180. (function (BABYLON) {
  18181. var BoundingBox = /** @class */ (function () {
  18182. /**
  18183. * Creates a new bounding box
  18184. * @param min defines the minimum vector (in local space)
  18185. * @param max defines the maximum vector (in local space)
  18186. */
  18187. function BoundingBox(min, max) {
  18188. this.vectorsWorld = new Array();
  18189. this.reConstruct(min, max);
  18190. }
  18191. // Methods
  18192. /**
  18193. * Recreates the entire bounding box from scratch
  18194. * @param min defines the new minimum vector (in local space)
  18195. * @param max defines the new maximum vector (in local space)
  18196. */
  18197. BoundingBox.prototype.reConstruct = function (min, max) {
  18198. this.minimum = min.clone();
  18199. this.maximum = max.clone();
  18200. // Bounding vectors
  18201. this.vectors = new Array();
  18202. this.vectors.push(this.minimum.clone());
  18203. this.vectors.push(this.maximum.clone());
  18204. this.vectors.push(this.minimum.clone());
  18205. this.vectors[2].x = this.maximum.x;
  18206. this.vectors.push(this.minimum.clone());
  18207. this.vectors[3].y = this.maximum.y;
  18208. this.vectors.push(this.minimum.clone());
  18209. this.vectors[4].z = this.maximum.z;
  18210. this.vectors.push(this.maximum.clone());
  18211. this.vectors[5].z = this.minimum.z;
  18212. this.vectors.push(this.maximum.clone());
  18213. this.vectors[6].x = this.minimum.x;
  18214. this.vectors.push(this.maximum.clone());
  18215. this.vectors[7].y = this.minimum.y;
  18216. // OBB
  18217. this.center = this.maximum.add(this.minimum).scale(0.5);
  18218. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18219. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18220. // World
  18221. for (var index = 0; index < this.vectors.length; index++) {
  18222. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18223. }
  18224. this.minimumWorld = BABYLON.Vector3.Zero();
  18225. this.maximumWorld = BABYLON.Vector3.Zero();
  18226. this.centerWorld = BABYLON.Vector3.Zero();
  18227. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18228. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18229. };
  18230. BoundingBox.prototype.getWorldMatrix = function () {
  18231. return this._worldMatrix;
  18232. };
  18233. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18234. this._worldMatrix.copyFrom(matrix);
  18235. return this;
  18236. };
  18237. BoundingBox.prototype._update = function (world) {
  18238. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18239. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18240. for (var index = 0; index < this.vectors.length; index++) {
  18241. var v = this.vectorsWorld[index];
  18242. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18243. if (v.x < this.minimumWorld.x)
  18244. this.minimumWorld.x = v.x;
  18245. if (v.y < this.minimumWorld.y)
  18246. this.minimumWorld.y = v.y;
  18247. if (v.z < this.minimumWorld.z)
  18248. this.minimumWorld.z = v.z;
  18249. if (v.x > this.maximumWorld.x)
  18250. this.maximumWorld.x = v.x;
  18251. if (v.y > this.maximumWorld.y)
  18252. this.maximumWorld.y = v.y;
  18253. if (v.z > this.maximumWorld.z)
  18254. this.maximumWorld.z = v.z;
  18255. }
  18256. // Extend
  18257. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18258. this.extendSizeWorld.scaleInPlace(0.5);
  18259. // OBB
  18260. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18261. this.centerWorld.scaleInPlace(0.5);
  18262. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18263. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18264. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18265. this._worldMatrix = world;
  18266. };
  18267. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18268. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18269. };
  18270. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18271. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18272. };
  18273. BoundingBox.prototype.intersectsPoint = function (point) {
  18274. var delta = -BABYLON.Epsilon;
  18275. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18276. return false;
  18277. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18278. return false;
  18279. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18280. return false;
  18281. return true;
  18282. };
  18283. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18284. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18285. };
  18286. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18287. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18288. return false;
  18289. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18290. return false;
  18291. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18292. return false;
  18293. return true;
  18294. };
  18295. // Statics
  18296. BoundingBox.Intersects = function (box0, box1) {
  18297. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18298. return false;
  18299. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18300. return false;
  18301. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18302. return false;
  18303. return true;
  18304. };
  18305. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18306. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18307. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18308. return (num <= (sphereRadius * sphereRadius));
  18309. };
  18310. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18311. for (var p = 0; p < 6; p++) {
  18312. for (var i = 0; i < 8; i++) {
  18313. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18314. return false;
  18315. }
  18316. }
  18317. }
  18318. return true;
  18319. };
  18320. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18321. for (var p = 0; p < 6; p++) {
  18322. var inCount = 8;
  18323. for (var i = 0; i < 8; i++) {
  18324. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18325. --inCount;
  18326. }
  18327. else {
  18328. break;
  18329. }
  18330. }
  18331. if (inCount === 0)
  18332. return false;
  18333. }
  18334. return true;
  18335. };
  18336. return BoundingBox;
  18337. }());
  18338. BABYLON.BoundingBox = BoundingBox;
  18339. })(BABYLON || (BABYLON = {}));
  18340. //# sourceMappingURL=babylon.boundingBox.js.map
  18341. var BABYLON;
  18342. (function (BABYLON) {
  18343. var computeBoxExtents = function (axis, box) {
  18344. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18345. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18346. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18347. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18348. var r = r0 + r1 + r2;
  18349. return {
  18350. min: p - r,
  18351. max: p + r
  18352. };
  18353. };
  18354. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18355. var axisOverlap = function (axis, box0, box1) {
  18356. var result0 = computeBoxExtents(axis, box0);
  18357. var result1 = computeBoxExtents(axis, box1);
  18358. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18359. };
  18360. var BoundingInfo = /** @class */ (function () {
  18361. function BoundingInfo(minimum, maximum) {
  18362. this.minimum = minimum;
  18363. this.maximum = maximum;
  18364. this._isLocked = false;
  18365. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18366. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18367. }
  18368. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18369. get: function () {
  18370. return this._isLocked;
  18371. },
  18372. set: function (value) {
  18373. this._isLocked = value;
  18374. },
  18375. enumerable: true,
  18376. configurable: true
  18377. });
  18378. // Methods
  18379. BoundingInfo.prototype.update = function (world) {
  18380. if (this._isLocked) {
  18381. return;
  18382. }
  18383. this.boundingBox._update(world);
  18384. this.boundingSphere._update(world);
  18385. };
  18386. /**
  18387. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18388. * @param center New center of the bounding info
  18389. * @param extend New extend of the bounding info
  18390. */
  18391. BoundingInfo.prototype.centerOn = function (center, extend) {
  18392. this.minimum = center.subtract(extend);
  18393. this.maximum = center.add(extend);
  18394. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18395. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18396. return this;
  18397. };
  18398. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18399. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18400. return false;
  18401. return this.boundingBox.isInFrustum(frustumPlanes);
  18402. };
  18403. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18404. /**
  18405. * Gets the world distance between the min and max points of the bounding box
  18406. */
  18407. get: function () {
  18408. var boundingBox = this.boundingBox;
  18409. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18410. return size.length();
  18411. },
  18412. enumerable: true,
  18413. configurable: true
  18414. });
  18415. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18416. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18417. };
  18418. BoundingInfo.prototype._checkCollision = function (collider) {
  18419. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18420. };
  18421. BoundingInfo.prototype.intersectsPoint = function (point) {
  18422. if (!this.boundingSphere.centerWorld) {
  18423. return false;
  18424. }
  18425. if (!this.boundingSphere.intersectsPoint(point)) {
  18426. return false;
  18427. }
  18428. if (!this.boundingBox.intersectsPoint(point)) {
  18429. return false;
  18430. }
  18431. return true;
  18432. };
  18433. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18434. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18435. return false;
  18436. }
  18437. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18438. return false;
  18439. }
  18440. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18441. return false;
  18442. }
  18443. if (!precise) {
  18444. return true;
  18445. }
  18446. var box0 = this.boundingBox;
  18447. var box1 = boundingInfo.boundingBox;
  18448. if (!axisOverlap(box0.directions[0], box0, box1))
  18449. return false;
  18450. if (!axisOverlap(box0.directions[1], box0, box1))
  18451. return false;
  18452. if (!axisOverlap(box0.directions[2], box0, box1))
  18453. return false;
  18454. if (!axisOverlap(box1.directions[0], box0, box1))
  18455. return false;
  18456. if (!axisOverlap(box1.directions[1], box0, box1))
  18457. return false;
  18458. if (!axisOverlap(box1.directions[2], box0, box1))
  18459. return false;
  18460. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18461. return false;
  18462. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18463. return false;
  18464. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18465. return false;
  18466. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18467. return false;
  18468. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18469. return false;
  18470. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18471. return false;
  18472. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18473. return false;
  18474. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18475. return false;
  18476. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18477. return false;
  18478. return true;
  18479. };
  18480. return BoundingInfo;
  18481. }());
  18482. BABYLON.BoundingInfo = BoundingInfo;
  18483. })(BABYLON || (BABYLON = {}));
  18484. //# sourceMappingURL=babylon.boundingInfo.js.map
  18485. var BABYLON;
  18486. (function (BABYLON) {
  18487. var TransformNode = /** @class */ (function (_super) {
  18488. __extends(TransformNode, _super);
  18489. function TransformNode(name, scene, isPure) {
  18490. if (scene === void 0) { scene = null; }
  18491. if (isPure === void 0) { isPure = true; }
  18492. var _this = _super.call(this, name, scene) || this;
  18493. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18494. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18495. _this._up = new BABYLON.Vector3(0, 1, 0);
  18496. _this._right = new BABYLON.Vector3(1, 0, 0);
  18497. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18498. // Properties
  18499. _this._rotation = BABYLON.Vector3.Zero();
  18500. _this._scaling = BABYLON.Vector3.One();
  18501. _this._isDirty = false;
  18502. /**
  18503. * Set the billboard mode. Default is 0.
  18504. *
  18505. * | Value | Type | Description |
  18506. * | --- | --- | --- |
  18507. * | 0 | BILLBOARDMODE_NONE | |
  18508. * | 1 | BILLBOARDMODE_X | |
  18509. * | 2 | BILLBOARDMODE_Y | |
  18510. * | 4 | BILLBOARDMODE_Z | |
  18511. * | 7 | BILLBOARDMODE_ALL | |
  18512. *
  18513. */
  18514. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18515. _this.scalingDeterminant = 1;
  18516. _this.infiniteDistance = false;
  18517. /**
  18518. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18519. * By default the system will update normals to compensate
  18520. */
  18521. _this.ignoreNonUniformScaling = false;
  18522. _this.position = BABYLON.Vector3.Zero();
  18523. _this._localWorld = BABYLON.Matrix.Zero();
  18524. _this._worldMatrix = BABYLON.Matrix.Zero();
  18525. _this._worldMatrixDeterminant = 0;
  18526. _this._absolutePosition = BABYLON.Vector3.Zero();
  18527. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18528. _this._postMultiplyPivotMatrix = false;
  18529. _this._isWorldMatrixFrozen = false;
  18530. /**
  18531. * An event triggered after the world matrix is updated
  18532. */
  18533. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18534. _this._nonUniformScaling = false;
  18535. if (isPure) {
  18536. _this.getScene().addTransformNode(_this);
  18537. }
  18538. return _this;
  18539. }
  18540. /**
  18541. * Gets a string idenfifying the name of the class
  18542. * @returns "TransformNode" string
  18543. */
  18544. TransformNode.prototype.getClassName = function () {
  18545. return "TransformNode";
  18546. };
  18547. Object.defineProperty(TransformNode.prototype, "rotation", {
  18548. /**
  18549. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18550. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18551. * Default : (0.0, 0.0, 0.0)
  18552. */
  18553. get: function () {
  18554. return this._rotation;
  18555. },
  18556. set: function (newRotation) {
  18557. this._rotation = newRotation;
  18558. },
  18559. enumerable: true,
  18560. configurable: true
  18561. });
  18562. Object.defineProperty(TransformNode.prototype, "scaling", {
  18563. /**
  18564. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18565. * Default : (1.0, 1.0, 1.0)
  18566. */
  18567. get: function () {
  18568. return this._scaling;
  18569. },
  18570. /**
  18571. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18572. * Default : (1.0, 1.0, 1.0)
  18573. */
  18574. set: function (newScaling) {
  18575. this._scaling = newScaling;
  18576. },
  18577. enumerable: true,
  18578. configurable: true
  18579. });
  18580. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18581. /**
  18582. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18583. * It's null by default.
  18584. * 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)
  18585. */
  18586. get: function () {
  18587. return this._rotationQuaternion;
  18588. },
  18589. set: function (quaternion) {
  18590. this._rotationQuaternion = quaternion;
  18591. //reset the rotation vector.
  18592. if (quaternion && this.rotation.length()) {
  18593. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18594. }
  18595. },
  18596. enumerable: true,
  18597. configurable: true
  18598. });
  18599. Object.defineProperty(TransformNode.prototype, "forward", {
  18600. /**
  18601. * The forward direction of that transform in world space.
  18602. */
  18603. get: function () {
  18604. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18605. },
  18606. enumerable: true,
  18607. configurable: true
  18608. });
  18609. Object.defineProperty(TransformNode.prototype, "up", {
  18610. /**
  18611. * The up direction of that transform in world space.
  18612. */
  18613. get: function () {
  18614. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18615. },
  18616. enumerable: true,
  18617. configurable: true
  18618. });
  18619. Object.defineProperty(TransformNode.prototype, "right", {
  18620. /**
  18621. * The right direction of that transform in world space.
  18622. */
  18623. get: function () {
  18624. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18625. },
  18626. enumerable: true,
  18627. configurable: true
  18628. });
  18629. /**
  18630. * Returns the latest update of the World matrix
  18631. * Returns a Matrix.
  18632. */
  18633. TransformNode.prototype.getWorldMatrix = function () {
  18634. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18635. this.computeWorldMatrix();
  18636. }
  18637. return this._worldMatrix;
  18638. };
  18639. /** @hidden */
  18640. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18641. return this._worldMatrixDeterminant;
  18642. };
  18643. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18644. /**
  18645. * Returns directly the latest state of the mesh World matrix.
  18646. * A Matrix is returned.
  18647. */
  18648. get: function () {
  18649. return this._worldMatrix;
  18650. },
  18651. enumerable: true,
  18652. configurable: true
  18653. });
  18654. /**
  18655. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18656. * Returns the TransformNode.
  18657. */
  18658. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18659. this._poseMatrix.copyFrom(matrix);
  18660. return this;
  18661. };
  18662. /**
  18663. * Returns the mesh Pose matrix.
  18664. * Returned object : Matrix
  18665. */
  18666. TransformNode.prototype.getPoseMatrix = function () {
  18667. return this._poseMatrix;
  18668. };
  18669. TransformNode.prototype._isSynchronized = function () {
  18670. if (this._isDirty) {
  18671. return false;
  18672. }
  18673. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18674. return false;
  18675. if (this._cache.pivotMatrixUpdated) {
  18676. return false;
  18677. }
  18678. if (this.infiniteDistance) {
  18679. return false;
  18680. }
  18681. if (!this._cache.position.equals(this.position))
  18682. return false;
  18683. if (this.rotationQuaternion) {
  18684. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18685. return false;
  18686. }
  18687. if (!this._cache.rotation.equals(this.rotation))
  18688. return false;
  18689. if (!this._cache.scaling.equals(this.scaling))
  18690. return false;
  18691. return true;
  18692. };
  18693. TransformNode.prototype._initCache = function () {
  18694. _super.prototype._initCache.call(this);
  18695. this._cache.localMatrixUpdated = false;
  18696. this._cache.position = BABYLON.Vector3.Zero();
  18697. this._cache.scaling = BABYLON.Vector3.Zero();
  18698. this._cache.rotation = BABYLON.Vector3.Zero();
  18699. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18700. this._cache.billboardMode = -1;
  18701. };
  18702. TransformNode.prototype.markAsDirty = function (property) {
  18703. if (property === "rotation") {
  18704. this.rotationQuaternion = null;
  18705. }
  18706. this._currentRenderId = Number.MAX_VALUE;
  18707. this._isDirty = true;
  18708. return this;
  18709. };
  18710. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18711. /**
  18712. * Returns the current mesh absolute position.
  18713. * Retuns a Vector3.
  18714. */
  18715. get: function () {
  18716. return this._absolutePosition;
  18717. },
  18718. enumerable: true,
  18719. configurable: true
  18720. });
  18721. /**
  18722. * Sets a new matrix to apply before all other transformation
  18723. * @param matrix defines the transform matrix
  18724. * @returns the current TransformNode
  18725. */
  18726. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18727. return this.setPivotMatrix(matrix, false);
  18728. };
  18729. /**
  18730. * Sets a new pivot matrix to the current node
  18731. * @param matrix defines the new pivot matrix to use
  18732. * @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
  18733. * @returns the current TransformNode
  18734. */
  18735. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18736. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18737. this._pivotMatrix = matrix.clone();
  18738. this._cache.pivotMatrixUpdated = true;
  18739. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18740. if (this._postMultiplyPivotMatrix) {
  18741. if (!this._pivotMatrixInverse) {
  18742. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18743. }
  18744. else {
  18745. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18746. }
  18747. }
  18748. return this;
  18749. };
  18750. /**
  18751. * Returns the mesh pivot matrix.
  18752. * Default : Identity.
  18753. * A Matrix is returned.
  18754. */
  18755. TransformNode.prototype.getPivotMatrix = function () {
  18756. return this._pivotMatrix;
  18757. };
  18758. /**
  18759. * Prevents the World matrix to be computed any longer.
  18760. * Returns the TransformNode.
  18761. */
  18762. TransformNode.prototype.freezeWorldMatrix = function () {
  18763. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18764. this.computeWorldMatrix(true);
  18765. this._isWorldMatrixFrozen = true;
  18766. return this;
  18767. };
  18768. /**
  18769. * Allows back the World matrix computation.
  18770. * Returns the TransformNode.
  18771. */
  18772. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18773. this._isWorldMatrixFrozen = false;
  18774. this.computeWorldMatrix(true);
  18775. return this;
  18776. };
  18777. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18778. /**
  18779. * True if the World matrix has been frozen.
  18780. * Returns a boolean.
  18781. */
  18782. get: function () {
  18783. return this._isWorldMatrixFrozen;
  18784. },
  18785. enumerable: true,
  18786. configurable: true
  18787. });
  18788. /**
  18789. * Retuns the mesh absolute position in the World.
  18790. * Returns a Vector3.
  18791. */
  18792. TransformNode.prototype.getAbsolutePosition = function () {
  18793. this.computeWorldMatrix();
  18794. return this._absolutePosition;
  18795. };
  18796. /**
  18797. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18798. * Returns the TransformNode.
  18799. */
  18800. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18801. if (!absolutePosition) {
  18802. return this;
  18803. }
  18804. var absolutePositionX;
  18805. var absolutePositionY;
  18806. var absolutePositionZ;
  18807. if (absolutePosition.x === undefined) {
  18808. if (arguments.length < 3) {
  18809. return this;
  18810. }
  18811. absolutePositionX = arguments[0];
  18812. absolutePositionY = arguments[1];
  18813. absolutePositionZ = arguments[2];
  18814. }
  18815. else {
  18816. absolutePositionX = absolutePosition.x;
  18817. absolutePositionY = absolutePosition.y;
  18818. absolutePositionZ = absolutePosition.z;
  18819. }
  18820. if (this.parent) {
  18821. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18822. invertParentWorldMatrix.invert();
  18823. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18824. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18825. }
  18826. else {
  18827. this.position.x = absolutePositionX;
  18828. this.position.y = absolutePositionY;
  18829. this.position.z = absolutePositionZ;
  18830. }
  18831. return this;
  18832. };
  18833. /**
  18834. * Sets the mesh position in its local space.
  18835. * Returns the TransformNode.
  18836. */
  18837. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18838. this.computeWorldMatrix();
  18839. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18840. return this;
  18841. };
  18842. /**
  18843. * Returns the mesh position in the local space from the current World matrix values.
  18844. * Returns a new Vector3.
  18845. */
  18846. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18847. this.computeWorldMatrix();
  18848. var invLocalWorldMatrix = this._localWorld.clone();
  18849. invLocalWorldMatrix.invert();
  18850. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18851. };
  18852. /**
  18853. * Translates the mesh along the passed Vector3 in its local space.
  18854. * Returns the TransformNode.
  18855. */
  18856. TransformNode.prototype.locallyTranslate = function (vector3) {
  18857. this.computeWorldMatrix(true);
  18858. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18859. return this;
  18860. };
  18861. /**
  18862. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18863. * @param targetPoint the position (must be in same space as current mesh) to look at
  18864. * @param yawCor optional yaw (y-axis) correction in radians
  18865. * @param pitchCor optional pitch (x-axis) correction in radians
  18866. * @param rollCor optional roll (z-axis) correction in radians
  18867. * @param space the choosen space of the target
  18868. * @returns the TransformNode.
  18869. */
  18870. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18871. if (yawCor === void 0) { yawCor = 0; }
  18872. if (pitchCor === void 0) { pitchCor = 0; }
  18873. if (rollCor === void 0) { rollCor = 0; }
  18874. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18875. var dv = TransformNode._lookAtVectorCache;
  18876. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18877. targetPoint.subtractToRef(pos, dv);
  18878. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18879. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18880. var pitch = Math.atan2(dv.y, len);
  18881. if (this.rotationQuaternion) {
  18882. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18883. }
  18884. else {
  18885. this.rotation.x = pitch + pitchCor;
  18886. this.rotation.y = yaw + yawCor;
  18887. this.rotation.z = rollCor;
  18888. }
  18889. return this;
  18890. };
  18891. /**
  18892. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18893. * This Vector3 is expressed in the World space.
  18894. */
  18895. TransformNode.prototype.getDirection = function (localAxis) {
  18896. var result = BABYLON.Vector3.Zero();
  18897. this.getDirectionToRef(localAxis, result);
  18898. return result;
  18899. };
  18900. /**
  18901. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18902. * localAxis is expressed in the mesh local space.
  18903. * result is computed in the Wordl space from the mesh World matrix.
  18904. * Returns the TransformNode.
  18905. */
  18906. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18907. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18908. return this;
  18909. };
  18910. /**
  18911. * Sets a new pivot point to the current node
  18912. * @param point defines the new pivot point to use
  18913. * @param space defines if the point is in world or local space (local by default)
  18914. * @returns the current TransformNode
  18915. */
  18916. TransformNode.prototype.setPivotPoint = function (point, space) {
  18917. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18918. if (this.getScene().getRenderId() == 0) {
  18919. this.computeWorldMatrix(true);
  18920. }
  18921. var wm = this.getWorldMatrix();
  18922. if (space == BABYLON.Space.WORLD) {
  18923. var tmat = BABYLON.Tmp.Matrix[0];
  18924. wm.invertToRef(tmat);
  18925. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18926. }
  18927. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18928. };
  18929. /**
  18930. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18931. */
  18932. TransformNode.prototype.getPivotPoint = function () {
  18933. var point = BABYLON.Vector3.Zero();
  18934. this.getPivotPointToRef(point);
  18935. return point;
  18936. };
  18937. /**
  18938. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18939. * Returns the TransformNode.
  18940. */
  18941. TransformNode.prototype.getPivotPointToRef = function (result) {
  18942. result.x = -this._pivotMatrix.m[12];
  18943. result.y = -this._pivotMatrix.m[13];
  18944. result.z = -this._pivotMatrix.m[14];
  18945. return this;
  18946. };
  18947. /**
  18948. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18949. */
  18950. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18951. var point = BABYLON.Vector3.Zero();
  18952. this.getAbsolutePivotPointToRef(point);
  18953. return point;
  18954. };
  18955. /**
  18956. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18957. * Returns the TransformNode.
  18958. */
  18959. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18960. result.x = this._pivotMatrix.m[12];
  18961. result.y = this._pivotMatrix.m[13];
  18962. result.z = this._pivotMatrix.m[14];
  18963. this.getPivotPointToRef(result);
  18964. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18965. return this;
  18966. };
  18967. /**
  18968. * Defines the passed node as the parent of the current node.
  18969. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18970. * Returns the TransformNode.
  18971. */
  18972. TransformNode.prototype.setParent = function (node) {
  18973. if (node === null) {
  18974. var rotation = BABYLON.Tmp.Quaternion[0];
  18975. var position = BABYLON.Tmp.Vector3[0];
  18976. var scale = BABYLON.Tmp.Vector3[1];
  18977. if (this.parent && this.parent.computeWorldMatrix) {
  18978. this.parent.computeWorldMatrix(true);
  18979. }
  18980. this.computeWorldMatrix(true);
  18981. this.getWorldMatrix().decompose(scale, rotation, position);
  18982. if (this.rotationQuaternion) {
  18983. this.rotationQuaternion.copyFrom(rotation);
  18984. }
  18985. else {
  18986. rotation.toEulerAnglesToRef(this.rotation);
  18987. }
  18988. this.scaling.x = scale.x;
  18989. this.scaling.y = scale.y;
  18990. this.scaling.z = scale.z;
  18991. this.position.x = position.x;
  18992. this.position.y = position.y;
  18993. this.position.z = position.z;
  18994. }
  18995. else {
  18996. var rotation = BABYLON.Tmp.Quaternion[0];
  18997. var position = BABYLON.Tmp.Vector3[0];
  18998. var scale = BABYLON.Tmp.Vector3[1];
  18999. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19000. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19001. this.computeWorldMatrix(true);
  19002. node.computeWorldMatrix(true);
  19003. node.getWorldMatrix().invertToRef(invParentMatrix);
  19004. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19005. diffMatrix.decompose(scale, rotation, position);
  19006. if (this.rotationQuaternion) {
  19007. this.rotationQuaternion.copyFrom(rotation);
  19008. }
  19009. else {
  19010. rotation.toEulerAnglesToRef(this.rotation);
  19011. }
  19012. this.position.x = position.x;
  19013. this.position.y = position.y;
  19014. this.position.z = position.z;
  19015. this.scaling.x = scale.x;
  19016. this.scaling.y = scale.y;
  19017. this.scaling.z = scale.z;
  19018. }
  19019. this.parent = node;
  19020. return this;
  19021. };
  19022. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19023. get: function () {
  19024. return this._nonUniformScaling;
  19025. },
  19026. enumerable: true,
  19027. configurable: true
  19028. });
  19029. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19030. if (this._nonUniformScaling === value) {
  19031. return false;
  19032. }
  19033. this._nonUniformScaling = value;
  19034. return true;
  19035. };
  19036. /**
  19037. * Attach the current TransformNode to another TransformNode associated with a bone
  19038. * @param bone Bone affecting the TransformNode
  19039. * @param affectedTransformNode TransformNode associated with the bone
  19040. */
  19041. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19042. this._transformToBoneReferal = affectedTransformNode;
  19043. this.parent = bone;
  19044. if (bone.getWorldMatrix().determinant() < 0) {
  19045. this.scalingDeterminant *= -1;
  19046. }
  19047. return this;
  19048. };
  19049. TransformNode.prototype.detachFromBone = function () {
  19050. if (!this.parent) {
  19051. return this;
  19052. }
  19053. if (this.parent.getWorldMatrix().determinant() < 0) {
  19054. this.scalingDeterminant *= -1;
  19055. }
  19056. this._transformToBoneReferal = null;
  19057. this.parent = null;
  19058. return this;
  19059. };
  19060. /**
  19061. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19062. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19063. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19064. * The passed axis is also normalized.
  19065. * Returns the TransformNode.
  19066. */
  19067. TransformNode.prototype.rotate = function (axis, amount, space) {
  19068. axis.normalize();
  19069. if (!this.rotationQuaternion) {
  19070. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19071. this.rotation = BABYLON.Vector3.Zero();
  19072. }
  19073. var rotationQuaternion;
  19074. if (!space || space === BABYLON.Space.LOCAL) {
  19075. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19076. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19077. }
  19078. else {
  19079. if (this.parent) {
  19080. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19081. invertParentWorldMatrix.invert();
  19082. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19083. }
  19084. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19085. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19086. }
  19087. return this;
  19088. };
  19089. /**
  19090. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19091. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19092. * The passed axis is also normalized.
  19093. * Returns the TransformNode.
  19094. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19095. */
  19096. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19097. axis.normalize();
  19098. if (!this.rotationQuaternion) {
  19099. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19100. this.rotation.copyFromFloats(0, 0, 0);
  19101. }
  19102. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19103. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19104. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19105. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19106. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19107. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19108. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19109. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19110. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19111. return this;
  19112. };
  19113. /**
  19114. * Translates the mesh along the axis vector for the passed distance in the given space.
  19115. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19116. * Returns the TransformNode.
  19117. */
  19118. TransformNode.prototype.translate = function (axis, distance, space) {
  19119. var displacementVector = axis.scale(distance);
  19120. if (!space || space === BABYLON.Space.LOCAL) {
  19121. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19122. this.setPositionWithLocalVector(tempV3);
  19123. }
  19124. else {
  19125. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19126. }
  19127. return this;
  19128. };
  19129. /**
  19130. * Adds a rotation step to the mesh current rotation.
  19131. * x, y, z are Euler angles expressed in radians.
  19132. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19133. * This means this rotation is made in the mesh local space only.
  19134. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19135. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19136. * ```javascript
  19137. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19138. * ```
  19139. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19140. * 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.
  19141. * Returns the TransformNode.
  19142. */
  19143. TransformNode.prototype.addRotation = function (x, y, z) {
  19144. var rotationQuaternion;
  19145. if (this.rotationQuaternion) {
  19146. rotationQuaternion = this.rotationQuaternion;
  19147. }
  19148. else {
  19149. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19150. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19151. }
  19152. var accumulation = BABYLON.Tmp.Quaternion[0];
  19153. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19154. rotationQuaternion.multiplyInPlace(accumulation);
  19155. if (!this.rotationQuaternion) {
  19156. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19157. }
  19158. return this;
  19159. };
  19160. /**
  19161. * Computes the mesh World matrix and returns it.
  19162. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19163. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19164. * If the parameter `force`is set to `true`, the actual computation is done.
  19165. * Returns the mesh World Matrix.
  19166. */
  19167. TransformNode.prototype.computeWorldMatrix = function (force) {
  19168. if (this._isWorldMatrixFrozen) {
  19169. return this._worldMatrix;
  19170. }
  19171. if (!force && this.isSynchronized(true)) {
  19172. this._currentRenderId = this.getScene().getRenderId();
  19173. return this._worldMatrix;
  19174. }
  19175. this._cache.position.copyFrom(this.position);
  19176. this._cache.scaling.copyFrom(this.scaling);
  19177. this._cache.pivotMatrixUpdated = false;
  19178. this._cache.billboardMode = this.billboardMode;
  19179. this._currentRenderId = this.getScene().getRenderId();
  19180. this._childRenderId = this.getScene().getRenderId();
  19181. this._isDirty = false;
  19182. // Scaling
  19183. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19184. // Rotation
  19185. //rotate, if quaternion is set and rotation was used
  19186. if (this.rotationQuaternion) {
  19187. var len = this.rotation.length();
  19188. if (len) {
  19189. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19190. this.rotation.copyFromFloats(0, 0, 0);
  19191. }
  19192. }
  19193. if (this.rotationQuaternion) {
  19194. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19195. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19196. }
  19197. else {
  19198. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19199. this._cache.rotation.copyFrom(this.rotation);
  19200. }
  19201. // Translation
  19202. var camera = this.getScene().activeCamera;
  19203. if (this.infiniteDistance && !this.parent && camera) {
  19204. var cameraWorldMatrix = camera.getWorldMatrix();
  19205. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19206. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19207. }
  19208. else {
  19209. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19210. }
  19211. // Composing transformations
  19212. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19213. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19214. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19215. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19216. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19217. // Need to decompose each rotation here
  19218. var currentPosition = BABYLON.Tmp.Vector3[3];
  19219. if (this.parent && this.parent.getWorldMatrix) {
  19220. if (this._transformToBoneReferal) {
  19221. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19222. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19223. }
  19224. else {
  19225. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19226. }
  19227. }
  19228. else {
  19229. currentPosition.copyFrom(this.position);
  19230. }
  19231. currentPosition.subtractInPlace(camera.globalPosition);
  19232. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19233. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19234. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19235. }
  19236. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19237. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19238. }
  19239. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19240. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19241. }
  19242. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19243. }
  19244. else {
  19245. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19246. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19247. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19248. }
  19249. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19250. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19251. }
  19252. // Local world
  19253. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19254. // Parent
  19255. if (this.parent && this.parent.getWorldMatrix) {
  19256. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19257. if (this._transformToBoneReferal) {
  19258. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19259. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19260. }
  19261. else {
  19262. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19263. }
  19264. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19265. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19266. this._worldMatrix.copyFrom(this._localWorld);
  19267. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19268. }
  19269. else {
  19270. if (this._transformToBoneReferal) {
  19271. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19272. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19273. }
  19274. else {
  19275. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19276. }
  19277. }
  19278. this._markSyncedWithParent();
  19279. }
  19280. else {
  19281. this._worldMatrix.copyFrom(this._localWorld);
  19282. }
  19283. // Post multiply inverse of pivotMatrix
  19284. if (this._postMultiplyPivotMatrix) {
  19285. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19286. }
  19287. // Normal matrix
  19288. if (!this.ignoreNonUniformScaling) {
  19289. if (this.scaling.isNonUniform) {
  19290. this._updateNonUniformScalingState(true);
  19291. }
  19292. else if (this.parent && this.parent._nonUniformScaling) {
  19293. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19294. }
  19295. else {
  19296. this._updateNonUniformScalingState(false);
  19297. }
  19298. }
  19299. else {
  19300. this._updateNonUniformScalingState(false);
  19301. }
  19302. this._afterComputeWorldMatrix();
  19303. // Absolute position
  19304. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19305. // Callbacks
  19306. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19307. if (!this._poseMatrix) {
  19308. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19309. }
  19310. // Cache the determinant
  19311. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19312. return this._worldMatrix;
  19313. };
  19314. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19315. };
  19316. /**
  19317. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19318. * @param func: callback function to add
  19319. *
  19320. * Returns the TransformNode.
  19321. */
  19322. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19323. this.onAfterWorldMatrixUpdateObservable.add(func);
  19324. return this;
  19325. };
  19326. /**
  19327. * Removes a registered callback function.
  19328. * Returns the TransformNode.
  19329. */
  19330. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19331. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19332. return this;
  19333. };
  19334. /**
  19335. * Clone the current transform node
  19336. * Returns the new transform node
  19337. * @param name Name of the new clone
  19338. * @param newParent New parent for the clone
  19339. * @param doNotCloneChildren Do not clone children hierarchy
  19340. */
  19341. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19342. var _this = this;
  19343. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19344. result.name = name;
  19345. result.id = name;
  19346. if (newParent) {
  19347. result.parent = newParent;
  19348. }
  19349. if (!doNotCloneChildren) {
  19350. // Children
  19351. var directDescendants = this.getDescendants(true);
  19352. for (var index = 0; index < directDescendants.length; index++) {
  19353. var child = directDescendants[index];
  19354. if (child.clone) {
  19355. child.clone(name + "." + child.name, result);
  19356. }
  19357. }
  19358. }
  19359. return result;
  19360. };
  19361. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19362. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19363. serializationObject.type = this.getClassName();
  19364. // Parent
  19365. if (this.parent) {
  19366. serializationObject.parentId = this.parent.id;
  19367. }
  19368. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19369. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19370. }
  19371. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19372. serializationObject.isEnabled = this.isEnabled();
  19373. // Parent
  19374. if (this.parent) {
  19375. serializationObject.parentId = this.parent.id;
  19376. }
  19377. return serializationObject;
  19378. };
  19379. // Statics
  19380. /**
  19381. * Returns a new TransformNode object parsed from the source provided.
  19382. * The parameter `parsedMesh` is the source.
  19383. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19384. */
  19385. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19386. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19387. if (BABYLON.Tags) {
  19388. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19389. }
  19390. if (parsedTransformNode.localMatrix) {
  19391. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19392. }
  19393. else if (parsedTransformNode.pivotMatrix) {
  19394. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19395. }
  19396. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19397. // Parent
  19398. if (parsedTransformNode.parentId) {
  19399. transformNode._waitingParentId = parsedTransformNode.parentId;
  19400. }
  19401. return transformNode;
  19402. };
  19403. /**
  19404. * Releases resources associated with this transform node.
  19405. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19406. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19407. */
  19408. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19409. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19410. // Animations
  19411. this.getScene().stopAnimation(this);
  19412. // Remove from scene
  19413. this.getScene().removeTransformNode(this);
  19414. this.onAfterWorldMatrixUpdateObservable.clear();
  19415. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19416. };
  19417. // Statics
  19418. TransformNode.BILLBOARDMODE_NONE = 0;
  19419. TransformNode.BILLBOARDMODE_X = 1;
  19420. TransformNode.BILLBOARDMODE_Y = 2;
  19421. TransformNode.BILLBOARDMODE_Z = 4;
  19422. TransformNode.BILLBOARDMODE_ALL = 7;
  19423. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19424. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19425. __decorate([
  19426. BABYLON.serializeAsVector3()
  19427. ], TransformNode.prototype, "_rotation", void 0);
  19428. __decorate([
  19429. BABYLON.serializeAsQuaternion()
  19430. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19431. __decorate([
  19432. BABYLON.serializeAsVector3()
  19433. ], TransformNode.prototype, "_scaling", void 0);
  19434. __decorate([
  19435. BABYLON.serialize()
  19436. ], TransformNode.prototype, "billboardMode", void 0);
  19437. __decorate([
  19438. BABYLON.serialize()
  19439. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19440. __decorate([
  19441. BABYLON.serialize()
  19442. ], TransformNode.prototype, "infiniteDistance", void 0);
  19443. __decorate([
  19444. BABYLON.serialize()
  19445. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19446. __decorate([
  19447. BABYLON.serializeAsVector3()
  19448. ], TransformNode.prototype, "position", void 0);
  19449. return TransformNode;
  19450. }(BABYLON.Node));
  19451. BABYLON.TransformNode = TransformNode;
  19452. })(BABYLON || (BABYLON = {}));
  19453. //# sourceMappingURL=babylon.transformNode.js.map
  19454. var BABYLON;
  19455. (function (BABYLON) {
  19456. /**
  19457. * Class used to store all common mesh properties
  19458. */
  19459. var AbstractMesh = /** @class */ (function (_super) {
  19460. __extends(AbstractMesh, _super);
  19461. // Constructor
  19462. /**
  19463. * Creates a new AbstractMesh
  19464. * @param name defines the name of the mesh
  19465. * @param scene defines the hosting scene
  19466. */
  19467. function AbstractMesh(name, scene) {
  19468. if (scene === void 0) { scene = null; }
  19469. var _this = _super.call(this, name, scene, false) || this;
  19470. _this._facetNb = 0; // facet number
  19471. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19472. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19473. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19474. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19475. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19476. _this._subDiv = {
  19477. max: 1,
  19478. X: 1,
  19479. Y: 1,
  19480. Z: 1
  19481. };
  19482. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19483. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19484. // Events
  19485. /**
  19486. * An event triggered when this mesh collides with another one
  19487. */
  19488. _this.onCollideObservable = new BABYLON.Observable();
  19489. /**
  19490. * An event triggered when the collision's position changes
  19491. */
  19492. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19493. /**
  19494. * An event triggered when material is changed
  19495. */
  19496. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19497. // Properties
  19498. /**
  19499. * Gets or sets the orientation for POV movement & rotation
  19500. */
  19501. _this.definedFacingForward = true;
  19502. /**
  19503. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19504. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19505. * * 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.
  19506. * @see http://doc.babylonjs.com/features/occlusionquery
  19507. */
  19508. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19509. /**
  19510. * 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:
  19511. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19512. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19513. * * 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.
  19514. * @see http://doc.babylonjs.com/features/occlusionquery
  19515. */
  19516. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19517. /**
  19518. * 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.
  19519. * The default value is -1 which means don't break the query and wait till the result
  19520. * @see http://doc.babylonjs.com/features/occlusionquery
  19521. */
  19522. _this.occlusionRetryCount = -1;
  19523. _this._occlusionInternalRetryCounter = 0;
  19524. _this._isOccluded = false;
  19525. _this._isOcclusionQueryInProgress = false;
  19526. _this._visibility = 1.0;
  19527. /** Gets or sets the alpha index used to sort transparent meshes
  19528. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19529. */
  19530. _this.alphaIndex = Number.MAX_VALUE;
  19531. /**
  19532. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19533. */
  19534. _this.isVisible = true;
  19535. /**
  19536. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19537. */
  19538. _this.isPickable = true;
  19539. /**
  19540. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19541. */
  19542. _this.showBoundingBox = false;
  19543. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19544. _this.showSubMeshesBoundingBox = false;
  19545. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19546. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19547. */
  19548. _this.isBlocker = false;
  19549. /**
  19550. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19551. */
  19552. _this.enablePointerMoveEvents = false;
  19553. /**
  19554. * Specifies the rendering group id for this mesh (0 by default)
  19555. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19556. */
  19557. _this.renderingGroupId = 0;
  19558. _this._receiveShadows = false;
  19559. /**
  19560. * Gets or sets a boolean indicating if the outline must be rendered as well
  19561. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19562. */
  19563. _this.renderOutline = false;
  19564. /** Defines color to use when rendering outline */
  19565. _this.outlineColor = BABYLON.Color3.Red();
  19566. /** Define width to use when rendering outline */
  19567. _this.outlineWidth = 0.02;
  19568. /**
  19569. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19570. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19571. */
  19572. _this.renderOverlay = false;
  19573. /** Defines color to use when rendering overlay */
  19574. _this.overlayColor = BABYLON.Color3.Red();
  19575. /** Defines alpha to use when rendering overlay */
  19576. _this.overlayAlpha = 0.5;
  19577. _this._hasVertexAlpha = false;
  19578. _this._useVertexColors = true;
  19579. _this._computeBonesUsingShaders = true;
  19580. _this._numBoneInfluencers = 4;
  19581. _this._applyFog = true;
  19582. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19583. _this.useOctreeForRenderingSelection = true;
  19584. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19585. _this.useOctreeForPicking = true;
  19586. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19587. _this.useOctreeForCollisions = true;
  19588. _this._layerMask = 0x0FFFFFFF;
  19589. /**
  19590. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19591. */
  19592. _this.alwaysSelectAsActiveMesh = false;
  19593. /**
  19594. * Gets or sets the current action manager
  19595. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19596. */
  19597. _this.actionManager = null;
  19598. /**
  19599. * Gets or sets impostor used for physic simulation
  19600. * @see http://doc.babylonjs.com/features/physics_engine
  19601. */
  19602. _this.physicsImpostor = null;
  19603. // Collisions
  19604. _this._checkCollisions = false;
  19605. _this._collisionMask = -1;
  19606. _this._collisionGroup = -1;
  19607. /**
  19608. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19609. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19610. */
  19611. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19612. /**
  19613. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19614. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19615. */
  19616. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19617. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19618. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19619. // Edges
  19620. /**
  19621. * Defines edge width used when edgesRenderer is enabled
  19622. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19623. */
  19624. _this.edgesWidth = 1;
  19625. /**
  19626. * Defines edge color used when edgesRenderer is enabled
  19627. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19628. */
  19629. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19630. // Cache
  19631. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19632. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19633. /** @hidden */
  19634. _this._renderId = 0;
  19635. /** @hidden */
  19636. _this._intersectionsInProgress = new Array();
  19637. /** @hidden */
  19638. _this._unIndexed = false;
  19639. /** @hidden */
  19640. _this._lightSources = new Array();
  19641. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19642. if (collidedMesh === void 0) { collidedMesh = null; }
  19643. //TODO move this to the collision coordinator!
  19644. if (_this.getScene().workerCollisions)
  19645. newPosition.multiplyInPlace(_this._collider._radius);
  19646. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19647. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19648. _this.position.addInPlace(_this._diffPositionForCollisions);
  19649. }
  19650. if (collidedMesh) {
  19651. _this.onCollideObservable.notifyObservers(collidedMesh);
  19652. }
  19653. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19654. };
  19655. _this.getScene().addMesh(_this);
  19656. _this._resyncLightSources();
  19657. return _this;
  19658. }
  19659. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19660. /**
  19661. * No billboard
  19662. */
  19663. get: function () {
  19664. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19665. },
  19666. enumerable: true,
  19667. configurable: true
  19668. });
  19669. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19670. /** Billboard on X axis */
  19671. get: function () {
  19672. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19673. },
  19674. enumerable: true,
  19675. configurable: true
  19676. });
  19677. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19678. /** Billboard on Y axis */
  19679. get: function () {
  19680. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19681. },
  19682. enumerable: true,
  19683. configurable: true
  19684. });
  19685. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19686. /** Billboard on Z axis */
  19687. get: function () {
  19688. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19689. },
  19690. enumerable: true,
  19691. configurable: true
  19692. });
  19693. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19694. /** Billboard on all axes */
  19695. get: function () {
  19696. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19697. },
  19698. enumerable: true,
  19699. configurable: true
  19700. });
  19701. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19702. /**
  19703. * Gets the number of facets in the mesh
  19704. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19705. */
  19706. get: function () {
  19707. return this._facetNb;
  19708. },
  19709. enumerable: true,
  19710. configurable: true
  19711. });
  19712. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19713. /**
  19714. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19715. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19716. */
  19717. get: function () {
  19718. return this._partitioningSubdivisions;
  19719. },
  19720. set: function (nb) {
  19721. this._partitioningSubdivisions = nb;
  19722. },
  19723. enumerable: true,
  19724. configurable: true
  19725. });
  19726. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19727. /**
  19728. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19729. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19730. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19731. */
  19732. get: function () {
  19733. return this._partitioningBBoxRatio;
  19734. },
  19735. set: function (ratio) {
  19736. this._partitioningBBoxRatio = ratio;
  19737. },
  19738. enumerable: true,
  19739. configurable: true
  19740. });
  19741. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19742. /**
  19743. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19744. * Works only for updatable meshes.
  19745. * Doesn't work with multi-materials
  19746. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19747. */
  19748. get: function () {
  19749. return this._facetDepthSort;
  19750. },
  19751. set: function (sort) {
  19752. this._facetDepthSort = sort;
  19753. },
  19754. enumerable: true,
  19755. configurable: true
  19756. });
  19757. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19758. /**
  19759. * The location (Vector3) where the facet depth sort must be computed from.
  19760. * By default, the active camera position.
  19761. * Used only when facet depth sort is enabled
  19762. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19763. */
  19764. get: function () {
  19765. return this._facetDepthSortFrom;
  19766. },
  19767. set: function (location) {
  19768. this._facetDepthSortFrom = location;
  19769. },
  19770. enumerable: true,
  19771. configurable: true
  19772. });
  19773. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19774. /**
  19775. * gets a boolean indicating if facetData is enabled
  19776. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19777. */
  19778. get: function () {
  19779. return this._facetDataEnabled;
  19780. },
  19781. enumerable: true,
  19782. configurable: true
  19783. });
  19784. /** @hidden */
  19785. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19786. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19787. return false;
  19788. }
  19789. this._markSubMeshesAsMiscDirty();
  19790. return true;
  19791. };
  19792. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19793. /** Set a function to call when this mesh collides with another one */
  19794. set: function (callback) {
  19795. if (this._onCollideObserver) {
  19796. this.onCollideObservable.remove(this._onCollideObserver);
  19797. }
  19798. this._onCollideObserver = this.onCollideObservable.add(callback);
  19799. },
  19800. enumerable: true,
  19801. configurable: true
  19802. });
  19803. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19804. /** Set a function to call when the collision's position changes */
  19805. set: function (callback) {
  19806. if (this._onCollisionPositionChangeObserver) {
  19807. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19808. }
  19809. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19810. },
  19811. enumerable: true,
  19812. configurable: true
  19813. });
  19814. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19815. /**
  19816. * 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
  19817. * @see http://doc.babylonjs.com/features/occlusionquery
  19818. */
  19819. get: function () {
  19820. return this._isOccluded;
  19821. },
  19822. set: function (value) {
  19823. this._isOccluded = value;
  19824. },
  19825. enumerable: true,
  19826. configurable: true
  19827. });
  19828. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19829. /**
  19830. * Flag to check the progress status of the query
  19831. * @see http://doc.babylonjs.com/features/occlusionquery
  19832. */
  19833. get: function () {
  19834. return this._isOcclusionQueryInProgress;
  19835. },
  19836. enumerable: true,
  19837. configurable: true
  19838. });
  19839. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19840. /**
  19841. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19842. */
  19843. get: function () {
  19844. return this._visibility;
  19845. },
  19846. /**
  19847. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19848. */
  19849. set: function (value) {
  19850. if (this._visibility === value) {
  19851. return;
  19852. }
  19853. this._visibility = value;
  19854. this._markSubMeshesAsMiscDirty();
  19855. },
  19856. enumerable: true,
  19857. configurable: true
  19858. });
  19859. Object.defineProperty(AbstractMesh.prototype, "material", {
  19860. /** Gets or sets current material */
  19861. get: function () {
  19862. return this._material;
  19863. },
  19864. set: function (value) {
  19865. if (this._material === value) {
  19866. return;
  19867. }
  19868. this._material = value;
  19869. if (this.onMaterialChangedObservable.hasObservers) {
  19870. this.onMaterialChangedObservable.notifyObservers(this);
  19871. }
  19872. if (!this.subMeshes) {
  19873. return;
  19874. }
  19875. this._unBindEffect();
  19876. },
  19877. enumerable: true,
  19878. configurable: true
  19879. });
  19880. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19881. /**
  19882. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19883. * @see http://doc.babylonjs.com/babylon101/shadows
  19884. */
  19885. get: function () {
  19886. return this._receiveShadows;
  19887. },
  19888. set: function (value) {
  19889. if (this._receiveShadows === value) {
  19890. return;
  19891. }
  19892. this._receiveShadows = value;
  19893. this._markSubMeshesAsLightDirty();
  19894. },
  19895. enumerable: true,
  19896. configurable: true
  19897. });
  19898. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19899. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19900. get: function () {
  19901. return this._hasVertexAlpha;
  19902. },
  19903. set: function (value) {
  19904. if (this._hasVertexAlpha === value) {
  19905. return;
  19906. }
  19907. this._hasVertexAlpha = value;
  19908. this._markSubMeshesAsAttributesDirty();
  19909. this._markSubMeshesAsMiscDirty();
  19910. },
  19911. enumerable: true,
  19912. configurable: true
  19913. });
  19914. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19915. /** 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) */
  19916. get: function () {
  19917. return this._useVertexColors;
  19918. },
  19919. set: function (value) {
  19920. if (this._useVertexColors === value) {
  19921. return;
  19922. }
  19923. this._useVertexColors = value;
  19924. this._markSubMeshesAsAttributesDirty();
  19925. },
  19926. enumerable: true,
  19927. configurable: true
  19928. });
  19929. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19930. /**
  19931. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19932. */
  19933. get: function () {
  19934. return this._computeBonesUsingShaders;
  19935. },
  19936. set: function (value) {
  19937. if (this._computeBonesUsingShaders === value) {
  19938. return;
  19939. }
  19940. this._computeBonesUsingShaders = value;
  19941. this._markSubMeshesAsAttributesDirty();
  19942. },
  19943. enumerable: true,
  19944. configurable: true
  19945. });
  19946. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19947. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19948. get: function () {
  19949. return this._numBoneInfluencers;
  19950. },
  19951. set: function (value) {
  19952. if (this._numBoneInfluencers === value) {
  19953. return;
  19954. }
  19955. this._numBoneInfluencers = value;
  19956. this._markSubMeshesAsAttributesDirty();
  19957. },
  19958. enumerable: true,
  19959. configurable: true
  19960. });
  19961. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19962. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19963. get: function () {
  19964. return this._applyFog;
  19965. },
  19966. set: function (value) {
  19967. if (this._applyFog === value) {
  19968. return;
  19969. }
  19970. this._applyFog = value;
  19971. this._markSubMeshesAsMiscDirty();
  19972. },
  19973. enumerable: true,
  19974. configurable: true
  19975. });
  19976. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19977. /**
  19978. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19979. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19980. */
  19981. get: function () {
  19982. return this._layerMask;
  19983. },
  19984. set: function (value) {
  19985. if (value === this._layerMask) {
  19986. return;
  19987. }
  19988. this._layerMask = value;
  19989. this._resyncLightSources();
  19990. },
  19991. enumerable: true,
  19992. configurable: true
  19993. });
  19994. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19995. /**
  19996. * Gets or sets a collision mask used to mask collisions (default is -1).
  19997. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19998. */
  19999. get: function () {
  20000. return this._collisionMask;
  20001. },
  20002. set: function (mask) {
  20003. this._collisionMask = !isNaN(mask) ? mask : -1;
  20004. },
  20005. enumerable: true,
  20006. configurable: true
  20007. });
  20008. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20009. /**
  20010. * Gets or sets the current collision group mask (-1 by default).
  20011. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20012. */
  20013. get: function () {
  20014. return this._collisionGroup;
  20015. },
  20016. set: function (mask) {
  20017. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20018. },
  20019. enumerable: true,
  20020. configurable: true
  20021. });
  20022. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20023. /** @hidden */
  20024. get: function () {
  20025. return null;
  20026. },
  20027. enumerable: true,
  20028. configurable: true
  20029. });
  20030. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20031. get: function () {
  20032. return this._skeleton;
  20033. },
  20034. /**
  20035. * Gets or sets a skeleton to apply skining transformations
  20036. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20037. */
  20038. set: function (value) {
  20039. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20040. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20041. }
  20042. if (value && value.needInitialSkinMatrix) {
  20043. value._registerMeshWithPoseMatrix(this);
  20044. }
  20045. this._skeleton = value;
  20046. if (!this._skeleton) {
  20047. this._bonesTransformMatrices = null;
  20048. }
  20049. this._markSubMeshesAsAttributesDirty();
  20050. },
  20051. enumerable: true,
  20052. configurable: true
  20053. });
  20054. /**
  20055. * Returns the string "AbstractMesh"
  20056. * @returns "AbstractMesh"
  20057. */
  20058. AbstractMesh.prototype.getClassName = function () {
  20059. return "AbstractMesh";
  20060. };
  20061. /**
  20062. * Gets a string representation of the current mesh
  20063. * @param fullDetails defines a boolean indicating if full details must be included
  20064. * @returns a string representation of the current mesh
  20065. */
  20066. AbstractMesh.prototype.toString = function (fullDetails) {
  20067. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20068. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20069. if (this._skeleton) {
  20070. ret += ", skeleton: " + this._skeleton.name;
  20071. }
  20072. if (fullDetails) {
  20073. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20074. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20075. }
  20076. return ret;
  20077. };
  20078. /** @hidden */
  20079. AbstractMesh.prototype._rebuild = function () {
  20080. if (this._occlusionQuery) {
  20081. this._occlusionQuery = null;
  20082. }
  20083. if (this._edgesRenderer) {
  20084. this._edgesRenderer._rebuild();
  20085. }
  20086. if (!this.subMeshes) {
  20087. return;
  20088. }
  20089. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20090. var subMesh = _a[_i];
  20091. subMesh._rebuild();
  20092. }
  20093. };
  20094. /** @hidden */
  20095. AbstractMesh.prototype._resyncLightSources = function () {
  20096. this._lightSources.length = 0;
  20097. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20098. var light = _a[_i];
  20099. if (!light.isEnabled()) {
  20100. continue;
  20101. }
  20102. if (light.canAffectMesh(this)) {
  20103. this._lightSources.push(light);
  20104. }
  20105. }
  20106. this._markSubMeshesAsLightDirty();
  20107. };
  20108. /** @hidden */
  20109. AbstractMesh.prototype._resyncLighSource = function (light) {
  20110. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20111. var index = this._lightSources.indexOf(light);
  20112. if (index === -1) {
  20113. if (!isIn) {
  20114. return;
  20115. }
  20116. this._lightSources.push(light);
  20117. }
  20118. else {
  20119. if (isIn) {
  20120. return;
  20121. }
  20122. this._lightSources.splice(index, 1);
  20123. }
  20124. this._markSubMeshesAsLightDirty();
  20125. };
  20126. /** @hidden */
  20127. AbstractMesh.prototype._unBindEffect = function () {
  20128. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20129. var subMesh = _a[_i];
  20130. subMesh.setEffect(null);
  20131. }
  20132. };
  20133. /** @hidden */
  20134. AbstractMesh.prototype._removeLightSource = function (light) {
  20135. var index = this._lightSources.indexOf(light);
  20136. if (index === -1) {
  20137. return;
  20138. }
  20139. this._lightSources.splice(index, 1);
  20140. this._markSubMeshesAsLightDirty();
  20141. };
  20142. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20143. if (!this.subMeshes) {
  20144. return;
  20145. }
  20146. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20147. var subMesh = _a[_i];
  20148. if (subMesh._materialDefines) {
  20149. func(subMesh._materialDefines);
  20150. }
  20151. }
  20152. };
  20153. /** @hidden */
  20154. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20155. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20156. };
  20157. /** @hidden */
  20158. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20159. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20160. };
  20161. /** @hidden */
  20162. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20163. if (!this.subMeshes) {
  20164. return;
  20165. }
  20166. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20167. var subMesh = _a[_i];
  20168. var material = subMesh.getMaterial();
  20169. if (material) {
  20170. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20171. }
  20172. }
  20173. };
  20174. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20175. /**
  20176. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20177. */
  20178. get: function () {
  20179. return this._scaling;
  20180. },
  20181. set: function (newScaling) {
  20182. this._scaling = newScaling;
  20183. if (this.physicsImpostor) {
  20184. this.physicsImpostor.forceUpdate();
  20185. }
  20186. },
  20187. enumerable: true,
  20188. configurable: true
  20189. });
  20190. // Methods
  20191. /**
  20192. * Disables the mesh edge rendering mode
  20193. * @returns the currentAbstractMesh
  20194. */
  20195. AbstractMesh.prototype.disableEdgesRendering = function () {
  20196. if (this._edgesRenderer) {
  20197. this._edgesRenderer.dispose();
  20198. this._edgesRenderer = null;
  20199. }
  20200. return this;
  20201. };
  20202. /**
  20203. * Enables the edge rendering mode on the mesh.
  20204. * This mode makes the mesh edges visible
  20205. * @param epsilon defines the maximal distance between two angles to detect a face
  20206. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20207. * @returns the currentAbstractMesh
  20208. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20209. */
  20210. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20211. if (epsilon === void 0) { epsilon = 0.95; }
  20212. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20213. this.disableEdgesRendering();
  20214. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20215. return this;
  20216. };
  20217. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20218. /**
  20219. * Gets the edgesRenderer associated with the mesh
  20220. */
  20221. get: function () {
  20222. return this._edgesRenderer;
  20223. },
  20224. enumerable: true,
  20225. configurable: true
  20226. });
  20227. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20228. /**
  20229. * Returns true if the mesh is blocked. Implemented by child classes
  20230. */
  20231. get: function () {
  20232. return false;
  20233. },
  20234. enumerable: true,
  20235. configurable: true
  20236. });
  20237. /**
  20238. * Returns the mesh itself by default. Implemented by child classes
  20239. * @param camera defines the camera to use to pick the right LOD level
  20240. * @returns the currentAbstractMesh
  20241. */
  20242. AbstractMesh.prototype.getLOD = function (camera) {
  20243. return this;
  20244. };
  20245. /**
  20246. * Returns 0 by default. Implemented by child classes
  20247. * @returns an integer
  20248. */
  20249. AbstractMesh.prototype.getTotalVertices = function () {
  20250. return 0;
  20251. };
  20252. /**
  20253. * Returns null by default. Implemented by child classes
  20254. * @returns null
  20255. */
  20256. AbstractMesh.prototype.getIndices = function () {
  20257. return null;
  20258. };
  20259. /**
  20260. * Returns the array of the requested vertex data kind. Implemented by child classes
  20261. * @param kind defines the vertex data kind to use
  20262. * @returns null
  20263. */
  20264. AbstractMesh.prototype.getVerticesData = function (kind) {
  20265. return null;
  20266. };
  20267. /**
  20268. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20269. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20270. * Note that a new underlying VertexBuffer object is created each call.
  20271. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20272. * @param kind defines vertex data kind:
  20273. * * BABYLON.VertexBuffer.PositionKind
  20274. * * BABYLON.VertexBuffer.UVKind
  20275. * * BABYLON.VertexBuffer.UV2Kind
  20276. * * BABYLON.VertexBuffer.UV3Kind
  20277. * * BABYLON.VertexBuffer.UV4Kind
  20278. * * BABYLON.VertexBuffer.UV5Kind
  20279. * * BABYLON.VertexBuffer.UV6Kind
  20280. * * BABYLON.VertexBuffer.ColorKind
  20281. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20282. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20283. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20284. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20285. * @param data defines the data source
  20286. * @param updatable defines if the data must be flagged as updatable (or static)
  20287. * @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
  20288. * @returns the current mesh
  20289. */
  20290. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20291. return this;
  20292. };
  20293. /**
  20294. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20295. * If the mesh has no geometry, it is simply returned as it is.
  20296. * @param kind defines vertex data kind:
  20297. * * BABYLON.VertexBuffer.PositionKind
  20298. * * BABYLON.VertexBuffer.UVKind
  20299. * * BABYLON.VertexBuffer.UV2Kind
  20300. * * BABYLON.VertexBuffer.UV3Kind
  20301. * * BABYLON.VertexBuffer.UV4Kind
  20302. * * BABYLON.VertexBuffer.UV5Kind
  20303. * * BABYLON.VertexBuffer.UV6Kind
  20304. * * BABYLON.VertexBuffer.ColorKind
  20305. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20306. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20307. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20308. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20309. * @param data defines the data source
  20310. * @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
  20311. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20312. * @returns the current mesh
  20313. */
  20314. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20315. return this;
  20316. };
  20317. /**
  20318. * Sets the mesh indices,
  20319. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20320. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20321. * @param totalVertices Defines the total number of vertices
  20322. * @returns the current mesh
  20323. */
  20324. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20325. return this;
  20326. };
  20327. /**
  20328. * Gets a boolean indicating if specific vertex data is present
  20329. * @param kind defines the vertex data kind to use
  20330. * @returns true is data kind is present
  20331. */
  20332. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20333. return false;
  20334. };
  20335. /**
  20336. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20337. * @returns a BoundingInfo
  20338. */
  20339. AbstractMesh.prototype.getBoundingInfo = function () {
  20340. if (this._masterMesh) {
  20341. return this._masterMesh.getBoundingInfo();
  20342. }
  20343. if (!this._boundingInfo) {
  20344. // this._boundingInfo is being created here
  20345. this._updateBoundingInfo();
  20346. }
  20347. // cannot be null.
  20348. return this._boundingInfo;
  20349. };
  20350. /**
  20351. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20352. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20353. * @returns the current mesh
  20354. */
  20355. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20356. if (includeDescendants === void 0) { includeDescendants = true; }
  20357. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20358. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20359. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20360. if (maxDimension === 0) {
  20361. return this;
  20362. }
  20363. var scale = 1 / maxDimension;
  20364. this.scaling.scaleInPlace(scale);
  20365. return this;
  20366. };
  20367. /**
  20368. * Overwrite the current bounding info
  20369. * @param boundingInfo defines the new bounding info
  20370. * @returns the current mesh
  20371. */
  20372. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20373. this._boundingInfo = boundingInfo;
  20374. return this;
  20375. };
  20376. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20377. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20378. get: function () {
  20379. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20380. },
  20381. enumerable: true,
  20382. configurable: true
  20383. });
  20384. /** @hidden */
  20385. AbstractMesh.prototype._preActivate = function () {
  20386. };
  20387. /** @hidden */
  20388. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20389. };
  20390. /** @hidden */
  20391. AbstractMesh.prototype._activate = function (renderId) {
  20392. this._renderId = renderId;
  20393. };
  20394. /**
  20395. * Gets the current world matrix
  20396. * @returns a Matrix
  20397. */
  20398. AbstractMesh.prototype.getWorldMatrix = function () {
  20399. if (this._masterMesh) {
  20400. return this._masterMesh.getWorldMatrix();
  20401. }
  20402. return _super.prototype.getWorldMatrix.call(this);
  20403. };
  20404. /** @hidden */
  20405. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20406. if (this._masterMesh) {
  20407. return this._masterMesh._getWorldMatrixDeterminant();
  20408. }
  20409. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20410. };
  20411. // ================================== Point of View Movement =================================
  20412. /**
  20413. * Perform relative position change from the point of view of behind the front of the mesh.
  20414. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20415. * Supports definition of mesh facing forward or backward
  20416. * @param amountRight defines the distance on the right axis
  20417. * @param amountUp defines the distance on the up axis
  20418. * @param amountForward defines the distance on the forward axis
  20419. * @returns the current mesh
  20420. */
  20421. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20422. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20423. return this;
  20424. };
  20425. /**
  20426. * Calculate relative position change from the point of view of behind the front of the mesh.
  20427. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20428. * Supports definition of mesh facing forward or backward
  20429. * @param amountRight defines the distance on the right axis
  20430. * @param amountUp defines the distance on the up axis
  20431. * @param amountForward defines the distance on the forward axis
  20432. * @returns the new displacement vector
  20433. */
  20434. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20435. var rotMatrix = new BABYLON.Matrix();
  20436. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20437. rotQuaternion.toRotationMatrix(rotMatrix);
  20438. var translationDelta = BABYLON.Vector3.Zero();
  20439. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20440. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20441. return translationDelta;
  20442. };
  20443. // ================================== Point of View Rotation =================================
  20444. /**
  20445. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20446. * Supports definition of mesh facing forward or backward
  20447. * @param flipBack defines the flip
  20448. * @param twirlClockwise defines the twirl
  20449. * @param tiltRight defines the tilt
  20450. * @returns the current mesh
  20451. */
  20452. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20453. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20454. return this;
  20455. };
  20456. /**
  20457. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20458. * Supports definition of mesh facing forward or backward.
  20459. * @param flipBack defines the flip
  20460. * @param twirlClockwise defines the twirl
  20461. * @param tiltRight defines the tilt
  20462. * @returns the new rotation vector
  20463. */
  20464. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20465. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20466. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20467. };
  20468. /**
  20469. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20470. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20471. * @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
  20472. * @returns the new bounding vectors
  20473. */
  20474. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20475. if (includeDescendants === void 0) { includeDescendants = true; }
  20476. if (predicate === void 0) { predicate = null; }
  20477. // Ensures that all world matrix will be recomputed.
  20478. this.getScene().incrementRenderId();
  20479. this.computeWorldMatrix(true);
  20480. var min;
  20481. var max;
  20482. var boundingInfo = this.getBoundingInfo();
  20483. if (!this.subMeshes) {
  20484. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20485. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20486. }
  20487. else {
  20488. min = boundingInfo.boundingBox.minimumWorld;
  20489. max = boundingInfo.boundingBox.maximumWorld;
  20490. }
  20491. if (includeDescendants) {
  20492. var descendants = this.getDescendants(false);
  20493. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20494. var descendant = descendants_1[_i];
  20495. var childMesh = descendant;
  20496. childMesh.computeWorldMatrix(true);
  20497. // Filters meshes based on custom predicate function.
  20498. if (predicate && !predicate(childMesh)) {
  20499. continue;
  20500. }
  20501. //make sure we have the needed params to get mix and max
  20502. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20503. continue;
  20504. }
  20505. var childBoundingInfo = childMesh.getBoundingInfo();
  20506. var boundingBox = childBoundingInfo.boundingBox;
  20507. var minBox = boundingBox.minimumWorld;
  20508. var maxBox = boundingBox.maximumWorld;
  20509. BABYLON.Tools.CheckExtends(minBox, min, max);
  20510. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20511. }
  20512. }
  20513. return {
  20514. min: min,
  20515. max: max
  20516. };
  20517. };
  20518. /** @hidden */
  20519. AbstractMesh.prototype._updateBoundingInfo = function () {
  20520. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20521. this._boundingInfo.update(this.worldMatrixFromCache);
  20522. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20523. return this;
  20524. };
  20525. /** @hidden */
  20526. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20527. if (!this.subMeshes) {
  20528. return this;
  20529. }
  20530. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20531. var subMesh = this.subMeshes[subIndex];
  20532. if (!subMesh.IsGlobal) {
  20533. subMesh.updateBoundingInfo(matrix);
  20534. }
  20535. }
  20536. return this;
  20537. };
  20538. /** @hidden */
  20539. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20540. // Bounding info
  20541. this._updateBoundingInfo();
  20542. };
  20543. /**
  20544. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20545. * A mesh is in the frustum if its bounding box intersects the frustum
  20546. * @param frustumPlanes defines the frustum to test
  20547. * @returns true if the mesh is in the frustum planes
  20548. */
  20549. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20550. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20551. };
  20552. /**
  20553. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20554. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20555. * @param frustumPlanes defines the frustum to test
  20556. * @returns true if the mesh is completely in the frustum planes
  20557. */
  20558. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20559. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20560. };
  20561. /**
  20562. * True if the mesh intersects another mesh or a SolidParticle object
  20563. * @param mesh defines a target mesh or SolidParticle to test
  20564. * @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)
  20565. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20566. * @returns true if there is an intersection
  20567. */
  20568. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20569. if (precise === void 0) { precise = false; }
  20570. if (!this._boundingInfo || !mesh._boundingInfo) {
  20571. return false;
  20572. }
  20573. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20574. return true;
  20575. }
  20576. if (includeDescendants) {
  20577. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20578. var child = _a[_i];
  20579. if (child.intersectsMesh(mesh, precise, true)) {
  20580. return true;
  20581. }
  20582. }
  20583. }
  20584. return false;
  20585. };
  20586. /**
  20587. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20588. * @param point defines the point to test
  20589. * @returns true if there is an intersection
  20590. */
  20591. AbstractMesh.prototype.intersectsPoint = function (point) {
  20592. if (!this._boundingInfo) {
  20593. return false;
  20594. }
  20595. return this._boundingInfo.intersectsPoint(point);
  20596. };
  20597. /**
  20598. * Gets the current physics impostor
  20599. * @see http://doc.babylonjs.com/features/physics_engine
  20600. * @returns a physics impostor or null
  20601. */
  20602. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20603. return this.physicsImpostor;
  20604. };
  20605. /**
  20606. * Gets the position of the current mesh in camera space
  20607. * @param camera defines the camera to use
  20608. * @returns a position
  20609. */
  20610. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20611. if (camera === void 0) { camera = null; }
  20612. if (!camera) {
  20613. camera = this.getScene().activeCamera;
  20614. }
  20615. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20616. };
  20617. /**
  20618. * Returns the distance from the mesh to the active camera
  20619. * @param camera defines the camera to use
  20620. * @returns the distance
  20621. */
  20622. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20623. if (camera === void 0) { camera = null; }
  20624. if (!camera) {
  20625. camera = this.getScene().activeCamera;
  20626. }
  20627. return this.absolutePosition.subtract(camera.position).length();
  20628. };
  20629. /**
  20630. * Apply a physic impulse to the mesh
  20631. * @param force defines the force to apply
  20632. * @param contactPoint defines where to apply the force
  20633. * @returns the current mesh
  20634. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20635. */
  20636. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20637. if (!this.physicsImpostor) {
  20638. return this;
  20639. }
  20640. this.physicsImpostor.applyImpulse(force, contactPoint);
  20641. return this;
  20642. };
  20643. /**
  20644. * Creates a physic joint between two meshes
  20645. * @param otherMesh defines the other mesh to use
  20646. * @param pivot1 defines the pivot to use on this mesh
  20647. * @param pivot2 defines the pivot to use on the other mesh
  20648. * @param options defines additional options (can be plugin dependent)
  20649. * @returns the current mesh
  20650. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20651. */
  20652. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20653. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20654. return this;
  20655. }
  20656. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20657. mainPivot: pivot1,
  20658. connectedPivot: pivot2,
  20659. nativeParams: options
  20660. });
  20661. return this;
  20662. };
  20663. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20664. // Collisions
  20665. /**
  20666. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20667. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20668. */
  20669. get: function () {
  20670. return this._checkCollisions;
  20671. },
  20672. set: function (collisionEnabled) {
  20673. this._checkCollisions = collisionEnabled;
  20674. if (this.getScene().workerCollisions) {
  20675. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20676. }
  20677. },
  20678. enumerable: true,
  20679. configurable: true
  20680. });
  20681. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20682. /**
  20683. * Gets Collider object used to compute collisions (not physics)
  20684. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20685. */
  20686. get: function () {
  20687. return this._collider;
  20688. },
  20689. enumerable: true,
  20690. configurable: true
  20691. });
  20692. /**
  20693. * Move the mesh using collision engine
  20694. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20695. * @param displacement defines the requested displacement vector
  20696. * @returns the current mesh
  20697. */
  20698. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20699. var globalPosition = this.getAbsolutePosition();
  20700. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20701. if (!this._collider) {
  20702. this._collider = new BABYLON.Collider();
  20703. }
  20704. this._collider._radius = this.ellipsoid;
  20705. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20706. return this;
  20707. };
  20708. // Submeshes octree
  20709. /**
  20710. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20711. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20712. * @param maxCapacity defines the maximum size of each block (64 by default)
  20713. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20714. * @returns the new octree
  20715. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20716. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20717. */
  20718. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20719. if (maxCapacity === void 0) { maxCapacity = 64; }
  20720. if (maxDepth === void 0) { maxDepth = 2; }
  20721. if (!this._submeshesOctree) {
  20722. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20723. }
  20724. this.computeWorldMatrix(true);
  20725. var boundingInfo = this.getBoundingInfo();
  20726. // Update octree
  20727. var bbox = boundingInfo.boundingBox;
  20728. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20729. return this._submeshesOctree;
  20730. };
  20731. // Collisions
  20732. /** @hidden */
  20733. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20734. this._generatePointsArray();
  20735. if (!this._positions) {
  20736. return this;
  20737. }
  20738. // Transformation
  20739. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20740. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20741. subMesh._lastColliderWorldVertices = [];
  20742. subMesh._trianglePlanes = [];
  20743. var start = subMesh.verticesStart;
  20744. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20745. for (var i = start; i < end; i++) {
  20746. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20747. }
  20748. }
  20749. // Collide
  20750. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20751. if (collider.collisionFound) {
  20752. collider.collidedMesh = this;
  20753. }
  20754. return this;
  20755. };
  20756. /** @hidden */
  20757. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20758. var subMeshes;
  20759. var len;
  20760. // Octrees
  20761. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20762. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20763. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20764. len = intersections.length;
  20765. subMeshes = intersections.data;
  20766. }
  20767. else {
  20768. subMeshes = this.subMeshes;
  20769. len = subMeshes.length;
  20770. }
  20771. for (var index = 0; index < len; index++) {
  20772. var subMesh = subMeshes[index];
  20773. // Bounding test
  20774. if (len > 1 && !subMesh._checkCollision(collider))
  20775. continue;
  20776. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20777. }
  20778. return this;
  20779. };
  20780. /** @hidden */
  20781. AbstractMesh.prototype._checkCollision = function (collider) {
  20782. // Bounding box test
  20783. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20784. return this;
  20785. // Transformation matrix
  20786. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20787. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20788. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20789. return this;
  20790. };
  20791. // Picking
  20792. /** @hidden */
  20793. AbstractMesh.prototype._generatePointsArray = function () {
  20794. return false;
  20795. };
  20796. /**
  20797. * Checks if the passed Ray intersects with the mesh
  20798. * @param ray defines the ray to use
  20799. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20800. * @returns the picking info
  20801. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20802. */
  20803. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20804. var pickingInfo = new BABYLON.PickingInfo();
  20805. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20806. return pickingInfo;
  20807. }
  20808. if (!this._generatePointsArray()) {
  20809. return pickingInfo;
  20810. }
  20811. var intersectInfo = null;
  20812. // Octrees
  20813. var subMeshes;
  20814. var len;
  20815. if (this._submeshesOctree && this.useOctreeForPicking) {
  20816. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20817. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20818. len = intersections.length;
  20819. subMeshes = intersections.data;
  20820. }
  20821. else {
  20822. subMeshes = this.subMeshes;
  20823. len = subMeshes.length;
  20824. }
  20825. for (var index = 0; index < len; index++) {
  20826. var subMesh = subMeshes[index];
  20827. // Bounding test
  20828. if (len > 1 && !subMesh.canIntersects(ray))
  20829. continue;
  20830. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20831. if (currentIntersectInfo) {
  20832. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20833. intersectInfo = currentIntersectInfo;
  20834. intersectInfo.subMeshId = index;
  20835. if (fastCheck) {
  20836. break;
  20837. }
  20838. }
  20839. }
  20840. }
  20841. if (intersectInfo) {
  20842. // Get picked point
  20843. var world = this.getWorldMatrix();
  20844. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20845. var direction = ray.direction.clone();
  20846. direction = direction.scale(intersectInfo.distance);
  20847. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20848. var pickedPoint = worldOrigin.add(worldDirection);
  20849. // Return result
  20850. pickingInfo.hit = true;
  20851. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20852. pickingInfo.pickedPoint = pickedPoint;
  20853. pickingInfo.pickedMesh = this;
  20854. pickingInfo.bu = intersectInfo.bu || 0;
  20855. pickingInfo.bv = intersectInfo.bv || 0;
  20856. pickingInfo.faceId = intersectInfo.faceId;
  20857. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20858. return pickingInfo;
  20859. }
  20860. return pickingInfo;
  20861. };
  20862. /**
  20863. * Clones the current mesh
  20864. * @param name defines the mesh name
  20865. * @param newParent defines the new mesh parent
  20866. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20867. * @returns the new mesh
  20868. */
  20869. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20870. return null;
  20871. };
  20872. /**
  20873. * Disposes all the submeshes of the current meshnp
  20874. * @returns the current mesh
  20875. */
  20876. AbstractMesh.prototype.releaseSubMeshes = function () {
  20877. if (this.subMeshes) {
  20878. while (this.subMeshes.length) {
  20879. this.subMeshes[0].dispose();
  20880. }
  20881. }
  20882. else {
  20883. this.subMeshes = new Array();
  20884. }
  20885. return this;
  20886. };
  20887. /**
  20888. * Releases resources associated with this abstract mesh.
  20889. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20890. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20891. */
  20892. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20893. var _this = this;
  20894. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20895. var index;
  20896. // Smart Array Retainers.
  20897. this.getScene().freeActiveMeshes();
  20898. this.getScene().freeRenderingGroups();
  20899. // Action manager
  20900. if (this.actionManager !== undefined && this.actionManager !== null) {
  20901. this.actionManager.dispose();
  20902. this.actionManager = null;
  20903. }
  20904. // Skeleton
  20905. this._skeleton = null;
  20906. // Physics
  20907. if (this.physicsImpostor) {
  20908. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20909. }
  20910. // Intersections in progress
  20911. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20912. var other = this._intersectionsInProgress[index];
  20913. var pos = other._intersectionsInProgress.indexOf(this);
  20914. other._intersectionsInProgress.splice(pos, 1);
  20915. }
  20916. this._intersectionsInProgress = [];
  20917. // Lights
  20918. var lights = this.getScene().lights;
  20919. lights.forEach(function (light) {
  20920. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20921. if (meshIndex !== -1) {
  20922. light.includedOnlyMeshes.splice(meshIndex, 1);
  20923. }
  20924. meshIndex = light.excludedMeshes.indexOf(_this);
  20925. if (meshIndex !== -1) {
  20926. light.excludedMeshes.splice(meshIndex, 1);
  20927. }
  20928. // Shadow generators
  20929. var generator = light.getShadowGenerator();
  20930. if (generator) {
  20931. var shadowMap = generator.getShadowMap();
  20932. if (shadowMap && shadowMap.renderList) {
  20933. meshIndex = shadowMap.renderList.indexOf(_this);
  20934. if (meshIndex !== -1) {
  20935. shadowMap.renderList.splice(meshIndex, 1);
  20936. }
  20937. }
  20938. }
  20939. });
  20940. // Edges
  20941. if (this._edgesRenderer) {
  20942. this._edgesRenderer.dispose();
  20943. this._edgesRenderer = null;
  20944. }
  20945. // SubMeshes
  20946. if (this.getClassName() !== "InstancedMesh") {
  20947. this.releaseSubMeshes();
  20948. }
  20949. // Octree
  20950. var sceneOctree = this.getScene().selectionOctree;
  20951. if (sceneOctree !== undefined && sceneOctree !== null) {
  20952. var index = sceneOctree.dynamicContent.indexOf(this);
  20953. if (index !== -1) {
  20954. sceneOctree.dynamicContent.splice(index, 1);
  20955. }
  20956. }
  20957. // Query
  20958. var engine = this.getScene().getEngine();
  20959. if (this._occlusionQuery) {
  20960. this._isOcclusionQueryInProgress = false;
  20961. engine.deleteQuery(this._occlusionQuery);
  20962. this._occlusionQuery = null;
  20963. }
  20964. // Engine
  20965. engine.wipeCaches();
  20966. // Remove from scene
  20967. this.getScene().removeMesh(this);
  20968. if (disposeMaterialAndTextures) {
  20969. if (this.material) {
  20970. this.material.dispose(false, true);
  20971. }
  20972. }
  20973. if (!doNotRecurse) {
  20974. // Particles
  20975. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20976. if (this.getScene().particleSystems[index].emitter === this) {
  20977. this.getScene().particleSystems[index].dispose();
  20978. index--;
  20979. }
  20980. }
  20981. }
  20982. // facet data
  20983. if (this._facetDataEnabled) {
  20984. this.disableFacetData();
  20985. }
  20986. this.onAfterWorldMatrixUpdateObservable.clear();
  20987. this.onCollideObservable.clear();
  20988. this.onCollisionPositionChangeObservable.clear();
  20989. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20990. };
  20991. /**
  20992. * Adds the passed mesh as a child to the current mesh
  20993. * @param mesh defines the child mesh
  20994. * @returns the current mesh
  20995. */
  20996. AbstractMesh.prototype.addChild = function (mesh) {
  20997. mesh.setParent(this);
  20998. return this;
  20999. };
  21000. /**
  21001. * Removes the passed mesh from the current mesh children list
  21002. * @param mesh defines the child mesh
  21003. * @returns the current mesh
  21004. */
  21005. AbstractMesh.prototype.removeChild = function (mesh) {
  21006. mesh.setParent(null);
  21007. return this;
  21008. };
  21009. // Facet data
  21010. /** @hidden */
  21011. AbstractMesh.prototype._initFacetData = function () {
  21012. if (!this._facetNormals) {
  21013. this._facetNormals = new Array();
  21014. }
  21015. if (!this._facetPositions) {
  21016. this._facetPositions = new Array();
  21017. }
  21018. if (!this._facetPartitioning) {
  21019. this._facetPartitioning = new Array();
  21020. }
  21021. this._facetNb = (this.getIndices().length / 3) | 0;
  21022. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21023. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21024. for (var f = 0; f < this._facetNb; f++) {
  21025. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21026. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21027. }
  21028. this._facetDataEnabled = true;
  21029. return this;
  21030. };
  21031. /**
  21032. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21033. * This method can be called within the render loop.
  21034. * 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
  21035. * @returns the current mesh
  21036. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21037. */
  21038. AbstractMesh.prototype.updateFacetData = function () {
  21039. if (!this._facetDataEnabled) {
  21040. this._initFacetData();
  21041. }
  21042. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21043. var indices = this.getIndices();
  21044. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21045. var bInfo = this.getBoundingInfo();
  21046. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21047. // init arrays, matrix and sort function on first call
  21048. this._facetDepthSortEnabled = true;
  21049. if (indices instanceof Uint16Array) {
  21050. this._depthSortedIndices = new Uint16Array(indices);
  21051. }
  21052. else if (indices instanceof Uint32Array) {
  21053. this._depthSortedIndices = new Uint32Array(indices);
  21054. }
  21055. else {
  21056. var needs32bits = false;
  21057. for (var i = 0; i < indices.length; i++) {
  21058. if (indices[i] > 65535) {
  21059. needs32bits = true;
  21060. break;
  21061. }
  21062. }
  21063. if (needs32bits) {
  21064. this._depthSortedIndices = new Uint32Array(indices);
  21065. }
  21066. else {
  21067. this._depthSortedIndices = new Uint16Array(indices);
  21068. }
  21069. }
  21070. this._facetDepthSortFunction = function (f1, f2) {
  21071. return (f2.sqDistance - f1.sqDistance);
  21072. };
  21073. if (!this._facetDepthSortFrom) {
  21074. var camera = this.getScene().activeCamera;
  21075. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21076. }
  21077. this._depthSortedFacets = [];
  21078. for (var f = 0; f < this._facetNb; f++) {
  21079. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21080. this._depthSortedFacets.push(depthSortedFacet);
  21081. }
  21082. this._invertedMatrix = BABYLON.Matrix.Identity();
  21083. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21084. }
  21085. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21086. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21087. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21088. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21089. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21090. this._subDiv.max = this._partitioningSubdivisions;
  21091. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21092. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21093. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21094. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21095. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21096. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21097. // set the parameters for ComputeNormals()
  21098. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21099. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21100. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21101. this._facetParameters.bInfo = bInfo;
  21102. this._facetParameters.bbSize = this._bbSize;
  21103. this._facetParameters.subDiv = this._subDiv;
  21104. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21105. this._facetParameters.depthSort = this._facetDepthSort;
  21106. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21107. this.computeWorldMatrix(true);
  21108. this._worldMatrix.invertToRef(this._invertedMatrix);
  21109. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21110. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21111. }
  21112. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21113. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21114. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21115. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21116. var l = (this._depthSortedIndices.length / 3) | 0;
  21117. for (var f = 0; f < l; f++) {
  21118. var sind = this._depthSortedFacets[f].ind;
  21119. this._depthSortedIndices[f * 3] = indices[sind];
  21120. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21121. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21122. }
  21123. this.updateIndices(this._depthSortedIndices);
  21124. }
  21125. return this;
  21126. };
  21127. /**
  21128. * Returns the facetLocalNormals array.
  21129. * The normals are expressed in the mesh local spac
  21130. * @returns an array of Vector3
  21131. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21132. */
  21133. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21134. if (!this._facetNormals) {
  21135. this.updateFacetData();
  21136. }
  21137. return this._facetNormals;
  21138. };
  21139. /**
  21140. * Returns the facetLocalPositions array.
  21141. * The facet positions are expressed in the mesh local space
  21142. * @returns an array of Vector3
  21143. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21144. */
  21145. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21146. if (!this._facetPositions) {
  21147. this.updateFacetData();
  21148. }
  21149. return this._facetPositions;
  21150. };
  21151. /**
  21152. * Returns the facetLocalPartioning array
  21153. * @returns an array of array of numbers
  21154. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21155. */
  21156. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21157. if (!this._facetPartitioning) {
  21158. this.updateFacetData();
  21159. }
  21160. return this._facetPartitioning;
  21161. };
  21162. /**
  21163. * Returns the i-th facet position in the world system.
  21164. * This method allocates a new Vector3 per call
  21165. * @param i defines the facet index
  21166. * @returns a new Vector3
  21167. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21168. */
  21169. AbstractMesh.prototype.getFacetPosition = function (i) {
  21170. var pos = BABYLON.Vector3.Zero();
  21171. this.getFacetPositionToRef(i, pos);
  21172. return pos;
  21173. };
  21174. /**
  21175. * Sets the reference Vector3 with the i-th facet position in the world system
  21176. * @param i defines the facet index
  21177. * @param ref defines the target vector
  21178. * @returns the current mesh
  21179. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21180. */
  21181. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21182. var localPos = (this.getFacetLocalPositions())[i];
  21183. var world = this.getWorldMatrix();
  21184. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21185. return this;
  21186. };
  21187. /**
  21188. * Returns the i-th facet normal in the world system.
  21189. * This method allocates a new Vector3 per call
  21190. * @param i defines the facet index
  21191. * @returns a new Vector3
  21192. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21193. */
  21194. AbstractMesh.prototype.getFacetNormal = function (i) {
  21195. var norm = BABYLON.Vector3.Zero();
  21196. this.getFacetNormalToRef(i, norm);
  21197. return norm;
  21198. };
  21199. /**
  21200. * Sets the reference Vector3 with the i-th facet normal in the world system
  21201. * @param i defines the facet index
  21202. * @param ref defines the target vector
  21203. * @returns the current mesh
  21204. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21205. */
  21206. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21207. var localNorm = (this.getFacetLocalNormals())[i];
  21208. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21209. return this;
  21210. };
  21211. /**
  21212. * 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)
  21213. * @param x defines x coordinate
  21214. * @param y defines y coordinate
  21215. * @param z defines z coordinate
  21216. * @returns the array of facet indexes
  21217. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21218. */
  21219. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21220. var bInfo = this.getBoundingInfo();
  21221. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21222. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21223. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21224. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21225. return null;
  21226. }
  21227. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21228. };
  21229. /**
  21230. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21231. * @param projected sets as the (x,y,z) world projection on the facet
  21232. * @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
  21233. * @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
  21234. * @param x defines x coordinate
  21235. * @param y defines y coordinate
  21236. * @param z defines z coordinate
  21237. * @returns the face index if found (or null instead)
  21238. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21239. */
  21240. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21241. if (checkFace === void 0) { checkFace = false; }
  21242. if (facing === void 0) { facing = true; }
  21243. var world = this.getWorldMatrix();
  21244. var invMat = BABYLON.Tmp.Matrix[5];
  21245. world.invertToRef(invMat);
  21246. var invVect = BABYLON.Tmp.Vector3[8];
  21247. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21248. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21249. if (projected) {
  21250. // tranform the local computed projected vector to world coordinates
  21251. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21252. }
  21253. return closest;
  21254. };
  21255. /**
  21256. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21257. * @param projected sets as the (x,y,z) local projection on the facet
  21258. * @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
  21259. * @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
  21260. * @param x defines x coordinate
  21261. * @param y defines y coordinate
  21262. * @param z defines z coordinate
  21263. * @returns the face index if found (or null instead)
  21264. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21265. */
  21266. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21267. if (checkFace === void 0) { checkFace = false; }
  21268. if (facing === void 0) { facing = true; }
  21269. var closest = null;
  21270. var tmpx = 0.0;
  21271. var tmpy = 0.0;
  21272. var tmpz = 0.0;
  21273. var d = 0.0; // tmp dot facet normal * facet position
  21274. var t0 = 0.0;
  21275. var projx = 0.0;
  21276. var projy = 0.0;
  21277. var projz = 0.0;
  21278. // Get all the facets in the same partitioning block than (x, y, z)
  21279. var facetPositions = this.getFacetLocalPositions();
  21280. var facetNormals = this.getFacetLocalNormals();
  21281. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21282. if (!facetsInBlock) {
  21283. return null;
  21284. }
  21285. // Get the closest facet to (x, y, z)
  21286. var shortest = Number.MAX_VALUE; // init distance vars
  21287. var tmpDistance = shortest;
  21288. var fib; // current facet in the block
  21289. var norm; // current facet normal
  21290. var p0; // current facet barycenter position
  21291. // loop on all the facets in the current partitioning block
  21292. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21293. fib = facetsInBlock[idx];
  21294. norm = facetNormals[fib];
  21295. p0 = facetPositions[fib];
  21296. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21297. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21298. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21299. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21300. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21301. projx = x + norm.x * t0;
  21302. projy = y + norm.y * t0;
  21303. projz = z + norm.z * t0;
  21304. tmpx = projx - x;
  21305. tmpy = projy - y;
  21306. tmpz = projz - z;
  21307. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21308. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21309. shortest = tmpDistance;
  21310. closest = fib;
  21311. if (projected) {
  21312. projected.x = projx;
  21313. projected.y = projy;
  21314. projected.z = projz;
  21315. }
  21316. }
  21317. }
  21318. }
  21319. return closest;
  21320. };
  21321. /**
  21322. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21323. * @returns the parameters
  21324. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21325. */
  21326. AbstractMesh.prototype.getFacetDataParameters = function () {
  21327. return this._facetParameters;
  21328. };
  21329. /**
  21330. * Disables the feature FacetData and frees the related memory
  21331. * @returns the current mesh
  21332. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21333. */
  21334. AbstractMesh.prototype.disableFacetData = function () {
  21335. if (this._facetDataEnabled) {
  21336. this._facetDataEnabled = false;
  21337. this._facetPositions = new Array();
  21338. this._facetNormals = new Array();
  21339. this._facetPartitioning = new Array();
  21340. this._facetParameters = null;
  21341. this._depthSortedIndices = new Uint32Array(0);
  21342. }
  21343. return this;
  21344. };
  21345. /**
  21346. * Updates the AbstractMesh indices array
  21347. * @param indices defines the data source
  21348. * @returns the current mesh
  21349. */
  21350. AbstractMesh.prototype.updateIndices = function (indices) {
  21351. return this;
  21352. };
  21353. /**
  21354. * Creates new normals data for the mesh
  21355. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21356. * @returns the current mesh
  21357. */
  21358. AbstractMesh.prototype.createNormals = function (updatable) {
  21359. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21360. var indices = this.getIndices();
  21361. var normals;
  21362. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21363. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21364. }
  21365. else {
  21366. normals = [];
  21367. }
  21368. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21369. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21370. return this;
  21371. };
  21372. /**
  21373. * Align the mesh with a normal
  21374. * @param normal defines the normal to use
  21375. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21376. * @returns the current mesh
  21377. */
  21378. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21379. if (!upDirection) {
  21380. upDirection = BABYLON.Axis.Y;
  21381. }
  21382. var axisX = BABYLON.Tmp.Vector3[0];
  21383. var axisZ = BABYLON.Tmp.Vector3[1];
  21384. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21385. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21386. if (this.rotationQuaternion) {
  21387. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21388. }
  21389. else {
  21390. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21391. }
  21392. return this;
  21393. };
  21394. /** @hidden */
  21395. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21396. var engine = this.getEngine();
  21397. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21398. this._isOccluded = false;
  21399. return;
  21400. }
  21401. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21402. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21403. if (isOcclusionQueryAvailable) {
  21404. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21405. this._isOcclusionQueryInProgress = false;
  21406. this._occlusionInternalRetryCounter = 0;
  21407. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21408. }
  21409. else {
  21410. this._occlusionInternalRetryCounter++;
  21411. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21412. this._isOcclusionQueryInProgress = false;
  21413. this._occlusionInternalRetryCounter = 0;
  21414. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21415. // if strict continue the last state of the object.
  21416. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21417. }
  21418. else {
  21419. return;
  21420. }
  21421. }
  21422. }
  21423. var scene = this.getScene();
  21424. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21425. if (!this._occlusionQuery) {
  21426. this._occlusionQuery = engine.createQuery();
  21427. }
  21428. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21429. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21430. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21431. this._isOcclusionQueryInProgress = true;
  21432. };
  21433. /** No occlusion */
  21434. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21435. /** Occlusion set to optimisitic */
  21436. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21437. /** Occlusion set to strict */
  21438. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21439. /** Use an accurante occlusion algorithm */
  21440. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21441. /** Use a conservative occlusion algorithm */
  21442. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21443. return AbstractMesh;
  21444. }(BABYLON.TransformNode));
  21445. BABYLON.AbstractMesh = AbstractMesh;
  21446. })(BABYLON || (BABYLON = {}));
  21447. //# sourceMappingURL=babylon.abstractMesh.js.map
  21448. var BABYLON;
  21449. (function (BABYLON) {
  21450. /**
  21451. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21452. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21453. * 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.
  21454. */
  21455. var Light = /** @class */ (function (_super) {
  21456. __extends(Light, _super);
  21457. /**
  21458. * Creates a Light object in the scene.
  21459. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21460. * @param name The firendly name of the light
  21461. * @param scene The scene the light belongs too
  21462. */
  21463. function Light(name, scene) {
  21464. var _this = _super.call(this, name, scene) || this;
  21465. /**
  21466. * Diffuse gives the basic color to an object.
  21467. */
  21468. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21469. /**
  21470. * Specular produces a highlight color on an object.
  21471. * Note: This is note affecting PBR materials.
  21472. */
  21473. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21474. /**
  21475. * Strength of the light.
  21476. * Note: By default it is define in the framework own unit.
  21477. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21478. */
  21479. _this.intensity = 1.0;
  21480. /**
  21481. * Defines how far from the source the light is impacting in scene units.
  21482. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21483. */
  21484. _this.range = Number.MAX_VALUE;
  21485. /**
  21486. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21487. * of light.
  21488. */
  21489. _this._photometricScale = 1.0;
  21490. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21491. _this._radius = 0.00001;
  21492. /**
  21493. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21494. * exceeding the number allowed of the materials.
  21495. */
  21496. _this.renderPriority = 0;
  21497. _this._shadowEnabled = true;
  21498. _this._excludeWithLayerMask = 0;
  21499. _this._includeOnlyWithLayerMask = 0;
  21500. _this._lightmapMode = 0;
  21501. /**
  21502. * @hidden Internal use only.
  21503. */
  21504. _this._excludedMeshesIds = new Array();
  21505. /**
  21506. * @hidden Internal use only.
  21507. */
  21508. _this._includedOnlyMeshesIds = new Array();
  21509. _this.getScene().addLight(_this);
  21510. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21511. _this._buildUniformLayout();
  21512. _this.includedOnlyMeshes = new Array();
  21513. _this.excludedMeshes = new Array();
  21514. _this._resyncMeshes();
  21515. return _this;
  21516. }
  21517. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21518. /**
  21519. * If every light affecting the material is in this lightmapMode,
  21520. * material.lightmapTexture adds or multiplies
  21521. * (depends on material.useLightmapAsShadowmap)
  21522. * after every other light calculations.
  21523. */
  21524. get: function () {
  21525. return Light._LIGHTMAP_DEFAULT;
  21526. },
  21527. enumerable: true,
  21528. configurable: true
  21529. });
  21530. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21531. /**
  21532. * material.lightmapTexture as only diffuse lighting from this light
  21533. * adds only specular lighting from this light
  21534. * adds dynamic shadows
  21535. */
  21536. get: function () {
  21537. return Light._LIGHTMAP_SPECULAR;
  21538. },
  21539. enumerable: true,
  21540. configurable: true
  21541. });
  21542. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21543. /**
  21544. * material.lightmapTexture as only lighting
  21545. * no light calculation from this light
  21546. * only adds dynamic shadows from this light
  21547. */
  21548. get: function () {
  21549. return Light._LIGHTMAP_SHADOWSONLY;
  21550. },
  21551. enumerable: true,
  21552. configurable: true
  21553. });
  21554. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21555. /**
  21556. * Each light type uses the default quantity according to its type:
  21557. * point/spot lights use luminous intensity
  21558. * directional lights use illuminance
  21559. */
  21560. get: function () {
  21561. return Light._INTENSITYMODE_AUTOMATIC;
  21562. },
  21563. enumerable: true,
  21564. configurable: true
  21565. });
  21566. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21567. /**
  21568. * lumen (lm)
  21569. */
  21570. get: function () {
  21571. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21572. },
  21573. enumerable: true,
  21574. configurable: true
  21575. });
  21576. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21577. /**
  21578. * candela (lm/sr)
  21579. */
  21580. get: function () {
  21581. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21582. },
  21583. enumerable: true,
  21584. configurable: true
  21585. });
  21586. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21587. /**
  21588. * lux (lm/m^2)
  21589. */
  21590. get: function () {
  21591. return Light._INTENSITYMODE_ILLUMINANCE;
  21592. },
  21593. enumerable: true,
  21594. configurable: true
  21595. });
  21596. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21597. /**
  21598. * nit (cd/m^2)
  21599. */
  21600. get: function () {
  21601. return Light._INTENSITYMODE_LUMINANCE;
  21602. },
  21603. enumerable: true,
  21604. configurable: true
  21605. });
  21606. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21607. /**
  21608. * Light type const id of the point light.
  21609. */
  21610. get: function () {
  21611. return Light._LIGHTTYPEID_POINTLIGHT;
  21612. },
  21613. enumerable: true,
  21614. configurable: true
  21615. });
  21616. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21617. /**
  21618. * Light type const id of the directional light.
  21619. */
  21620. get: function () {
  21621. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21622. },
  21623. enumerable: true,
  21624. configurable: true
  21625. });
  21626. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21627. /**
  21628. * Light type const id of the spot light.
  21629. */
  21630. get: function () {
  21631. return Light._LIGHTTYPEID_SPOTLIGHT;
  21632. },
  21633. enumerable: true,
  21634. configurable: true
  21635. });
  21636. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21637. /**
  21638. * Light type const id of the hemispheric light.
  21639. */
  21640. get: function () {
  21641. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21642. },
  21643. enumerable: true,
  21644. configurable: true
  21645. });
  21646. Object.defineProperty(Light.prototype, "intensityMode", {
  21647. /**
  21648. * Gets the photometric scale used to interpret the intensity.
  21649. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21650. */
  21651. get: function () {
  21652. return this._intensityMode;
  21653. },
  21654. /**
  21655. * Sets the photometric scale used to interpret the intensity.
  21656. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21657. */
  21658. set: function (value) {
  21659. this._intensityMode = value;
  21660. this._computePhotometricScale();
  21661. },
  21662. enumerable: true,
  21663. configurable: true
  21664. });
  21665. ;
  21666. ;
  21667. Object.defineProperty(Light.prototype, "radius", {
  21668. /**
  21669. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21670. */
  21671. get: function () {
  21672. return this._radius;
  21673. },
  21674. /**
  21675. * sets the light radius used by PBR Materials to simulate soft area lights.
  21676. */
  21677. set: function (value) {
  21678. this._radius = value;
  21679. this._computePhotometricScale();
  21680. },
  21681. enumerable: true,
  21682. configurable: true
  21683. });
  21684. ;
  21685. ;
  21686. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21687. /**
  21688. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21689. * the current shadow generator.
  21690. */
  21691. get: function () {
  21692. return this._shadowEnabled;
  21693. },
  21694. /**
  21695. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21696. * the current shadow generator.
  21697. */
  21698. set: function (value) {
  21699. if (this._shadowEnabled === value) {
  21700. return;
  21701. }
  21702. this._shadowEnabled = value;
  21703. this._markMeshesAsLightDirty();
  21704. },
  21705. enumerable: true,
  21706. configurable: true
  21707. });
  21708. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21709. /**
  21710. * Gets the only meshes impacted by this light.
  21711. */
  21712. get: function () {
  21713. return this._includedOnlyMeshes;
  21714. },
  21715. /**
  21716. * Sets the only meshes impacted by this light.
  21717. */
  21718. set: function (value) {
  21719. this._includedOnlyMeshes = value;
  21720. this._hookArrayForIncludedOnly(value);
  21721. },
  21722. enumerable: true,
  21723. configurable: true
  21724. });
  21725. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21726. /**
  21727. * Gets the meshes not impacted by this light.
  21728. */
  21729. get: function () {
  21730. return this._excludedMeshes;
  21731. },
  21732. /**
  21733. * Sets the meshes not impacted by this light.
  21734. */
  21735. set: function (value) {
  21736. this._excludedMeshes = value;
  21737. this._hookArrayForExcluded(value);
  21738. },
  21739. enumerable: true,
  21740. configurable: true
  21741. });
  21742. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21743. /**
  21744. * Gets the layer id use to find what meshes are not impacted by the light.
  21745. * Inactive if 0
  21746. */
  21747. get: function () {
  21748. return this._excludeWithLayerMask;
  21749. },
  21750. /**
  21751. * Sets the layer id use to find what meshes are not impacted by the light.
  21752. * Inactive if 0
  21753. */
  21754. set: function (value) {
  21755. this._excludeWithLayerMask = value;
  21756. this._resyncMeshes();
  21757. },
  21758. enumerable: true,
  21759. configurable: true
  21760. });
  21761. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21762. /**
  21763. * Gets the layer id use to find what meshes are impacted by the light.
  21764. * Inactive if 0
  21765. */
  21766. get: function () {
  21767. return this._includeOnlyWithLayerMask;
  21768. },
  21769. /**
  21770. * Sets the layer id use to find what meshes are impacted by the light.
  21771. * Inactive if 0
  21772. */
  21773. set: function (value) {
  21774. this._includeOnlyWithLayerMask = value;
  21775. this._resyncMeshes();
  21776. },
  21777. enumerable: true,
  21778. configurable: true
  21779. });
  21780. Object.defineProperty(Light.prototype, "lightmapMode", {
  21781. /**
  21782. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21783. */
  21784. get: function () {
  21785. return this._lightmapMode;
  21786. },
  21787. /**
  21788. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21789. */
  21790. set: function (value) {
  21791. if (this._lightmapMode === value) {
  21792. return;
  21793. }
  21794. this._lightmapMode = value;
  21795. this._markMeshesAsLightDirty();
  21796. },
  21797. enumerable: true,
  21798. configurable: true
  21799. });
  21800. /**
  21801. * Returns the string "Light".
  21802. * @returns the class name
  21803. */
  21804. Light.prototype.getClassName = function () {
  21805. return "Light";
  21806. };
  21807. /**
  21808. * Converts the light information to a readable string for debug purpose.
  21809. * @param fullDetails Supports for multiple levels of logging within scene loading
  21810. * @returns the human readable light info
  21811. */
  21812. Light.prototype.toString = function (fullDetails) {
  21813. var ret = "Name: " + this.name;
  21814. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21815. if (this.animations) {
  21816. for (var i = 0; i < this.animations.length; i++) {
  21817. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21818. }
  21819. }
  21820. if (fullDetails) {
  21821. }
  21822. return ret;
  21823. };
  21824. /**
  21825. * Set the enabled state of this node.
  21826. * @param value - the new enabled state
  21827. */
  21828. Light.prototype.setEnabled = function (value) {
  21829. _super.prototype.setEnabled.call(this, value);
  21830. this._resyncMeshes();
  21831. };
  21832. /**
  21833. * Returns the Light associated shadow generator if any.
  21834. * @return the associated shadow generator.
  21835. */
  21836. Light.prototype.getShadowGenerator = function () {
  21837. return this._shadowGenerator;
  21838. };
  21839. /**
  21840. * Returns a Vector3, the absolute light position in the World.
  21841. * @returns the world space position of the light
  21842. */
  21843. Light.prototype.getAbsolutePosition = function () {
  21844. return BABYLON.Vector3.Zero();
  21845. };
  21846. /**
  21847. * Specifies if the light will affect the passed mesh.
  21848. * @param mesh The mesh to test against the light
  21849. * @return true the mesh is affected otherwise, false.
  21850. */
  21851. Light.prototype.canAffectMesh = function (mesh) {
  21852. if (!mesh) {
  21853. return true;
  21854. }
  21855. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21856. return false;
  21857. }
  21858. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21859. return false;
  21860. }
  21861. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21862. return false;
  21863. }
  21864. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21865. return false;
  21866. }
  21867. return true;
  21868. };
  21869. /**
  21870. * Computes and Returns the light World matrix.
  21871. * @returns the world matrix
  21872. */
  21873. Light.prototype.getWorldMatrix = function () {
  21874. this._currentRenderId = this.getScene().getRenderId();
  21875. this._childRenderId = this._currentRenderId;
  21876. var worldMatrix = this._getWorldMatrix();
  21877. if (this.parent && this.parent.getWorldMatrix) {
  21878. if (!this._parentedWorldMatrix) {
  21879. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21880. }
  21881. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21882. this._markSyncedWithParent();
  21883. return this._parentedWorldMatrix;
  21884. }
  21885. return worldMatrix;
  21886. };
  21887. /**
  21888. * Sort function to order lights for rendering.
  21889. * @param a First Light object to compare to second.
  21890. * @param b Second Light object to compare first.
  21891. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21892. */
  21893. Light.CompareLightsPriority = function (a, b) {
  21894. //shadow-casting lights have priority over non-shadow-casting lights
  21895. //the renderPrioirty is a secondary sort criterion
  21896. if (a.shadowEnabled !== b.shadowEnabled) {
  21897. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21898. }
  21899. return b.renderPriority - a.renderPriority;
  21900. };
  21901. /**
  21902. * Releases resources associated with this node.
  21903. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21904. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21905. */
  21906. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21907. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21908. if (this._shadowGenerator) {
  21909. this._shadowGenerator.dispose();
  21910. this._shadowGenerator = null;
  21911. }
  21912. // Animations
  21913. this.getScene().stopAnimation(this);
  21914. // Remove from meshes
  21915. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21916. var mesh = _a[_i];
  21917. mesh._removeLightSource(this);
  21918. }
  21919. this._uniformBuffer.dispose();
  21920. // Remove from scene
  21921. this.getScene().removeLight(this);
  21922. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21923. };
  21924. /**
  21925. * Returns the light type ID (integer).
  21926. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21927. */
  21928. Light.prototype.getTypeID = function () {
  21929. return 0;
  21930. };
  21931. /**
  21932. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21933. * @returns the scaled intensity in intensity mode unit
  21934. */
  21935. Light.prototype.getScaledIntensity = function () {
  21936. return this._photometricScale * this.intensity;
  21937. };
  21938. /**
  21939. * Returns a new Light object, named "name", from the current one.
  21940. * @param name The name of the cloned light
  21941. * @returns the new created light
  21942. */
  21943. Light.prototype.clone = function (name) {
  21944. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21945. if (!constructor) {
  21946. return null;
  21947. }
  21948. return BABYLON.SerializationHelper.Clone(constructor, this);
  21949. };
  21950. /**
  21951. * Serializes the current light into a Serialization object.
  21952. * @returns the serialized object.
  21953. */
  21954. Light.prototype.serialize = function () {
  21955. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21956. // Type
  21957. serializationObject.type = this.getTypeID();
  21958. // Parent
  21959. if (this.parent) {
  21960. serializationObject.parentId = this.parent.id;
  21961. }
  21962. // Inclusion / exclusions
  21963. if (this.excludedMeshes.length > 0) {
  21964. serializationObject.excludedMeshesIds = [];
  21965. this.excludedMeshes.forEach(function (mesh) {
  21966. serializationObject.excludedMeshesIds.push(mesh.id);
  21967. });
  21968. }
  21969. if (this.includedOnlyMeshes.length > 0) {
  21970. serializationObject.includedOnlyMeshesIds = [];
  21971. this.includedOnlyMeshes.forEach(function (mesh) {
  21972. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21973. });
  21974. }
  21975. // Animations
  21976. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21977. serializationObject.ranges = this.serializeAnimationRanges();
  21978. return serializationObject;
  21979. };
  21980. /**
  21981. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21982. * This new light is named "name" and added to the passed scene.
  21983. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21984. * @param name The friendly name of the light
  21985. * @param scene The scene the new light will belong to
  21986. * @returns the constructor function
  21987. */
  21988. Light.GetConstructorFromName = function (type, name, scene) {
  21989. switch (type) {
  21990. case 0:
  21991. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21992. case 1:
  21993. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21994. case 2:
  21995. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21996. case 3:
  21997. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21998. }
  21999. return null;
  22000. };
  22001. /**
  22002. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22003. * @param parsedLight The JSON representation of the light
  22004. * @param scene The scene to create the parsed light in
  22005. * @returns the created light after parsing
  22006. */
  22007. Light.Parse = function (parsedLight, scene) {
  22008. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22009. if (!constructor) {
  22010. return null;
  22011. }
  22012. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22013. // Inclusion / exclusions
  22014. if (parsedLight.excludedMeshesIds) {
  22015. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22016. }
  22017. if (parsedLight.includedOnlyMeshesIds) {
  22018. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22019. }
  22020. // Parent
  22021. if (parsedLight.parentId) {
  22022. light._waitingParentId = parsedLight.parentId;
  22023. }
  22024. // Animations
  22025. if (parsedLight.animations) {
  22026. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22027. var parsedAnimation = parsedLight.animations[animationIndex];
  22028. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22029. }
  22030. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22031. }
  22032. if (parsedLight.autoAnimate) {
  22033. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22034. }
  22035. return light;
  22036. };
  22037. Light.prototype._hookArrayForExcluded = function (array) {
  22038. var _this = this;
  22039. var oldPush = array.push;
  22040. array.push = function () {
  22041. var items = [];
  22042. for (var _i = 0; _i < arguments.length; _i++) {
  22043. items[_i] = arguments[_i];
  22044. }
  22045. var result = oldPush.apply(array, items);
  22046. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22047. var item = items_1[_a];
  22048. item._resyncLighSource(_this);
  22049. }
  22050. return result;
  22051. };
  22052. var oldSplice = array.splice;
  22053. array.splice = function (index, deleteCount) {
  22054. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22055. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22056. var item = deleted_1[_i];
  22057. item._resyncLighSource(_this);
  22058. }
  22059. return deleted;
  22060. };
  22061. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22062. var item = array_1[_i];
  22063. item._resyncLighSource(this);
  22064. }
  22065. };
  22066. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22067. var _this = this;
  22068. var oldPush = array.push;
  22069. array.push = function () {
  22070. var items = [];
  22071. for (var _i = 0; _i < arguments.length; _i++) {
  22072. items[_i] = arguments[_i];
  22073. }
  22074. var result = oldPush.apply(array, items);
  22075. _this._resyncMeshes();
  22076. return result;
  22077. };
  22078. var oldSplice = array.splice;
  22079. array.splice = function (index, deleteCount) {
  22080. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22081. _this._resyncMeshes();
  22082. return deleted;
  22083. };
  22084. this._resyncMeshes();
  22085. };
  22086. Light.prototype._resyncMeshes = function () {
  22087. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22088. var mesh = _a[_i];
  22089. mesh._resyncLighSource(this);
  22090. }
  22091. };
  22092. /**
  22093. * Forces the meshes to update their light related information in their rendering used effects
  22094. * @hidden Internal Use Only
  22095. */
  22096. Light.prototype._markMeshesAsLightDirty = function () {
  22097. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22098. var mesh = _a[_i];
  22099. if (mesh._lightSources.indexOf(this) !== -1) {
  22100. mesh._markSubMeshesAsLightDirty();
  22101. }
  22102. }
  22103. };
  22104. /**
  22105. * Recomputes the cached photometric scale if needed.
  22106. */
  22107. Light.prototype._computePhotometricScale = function () {
  22108. this._photometricScale = this._getPhotometricScale();
  22109. this.getScene().resetCachedMaterial();
  22110. };
  22111. /**
  22112. * Returns the Photometric Scale according to the light type and intensity mode.
  22113. */
  22114. Light.prototype._getPhotometricScale = function () {
  22115. var photometricScale = 0.0;
  22116. var lightTypeID = this.getTypeID();
  22117. //get photometric mode
  22118. var photometricMode = this.intensityMode;
  22119. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22120. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22121. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22122. }
  22123. else {
  22124. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22125. }
  22126. }
  22127. //compute photometric scale
  22128. switch (lightTypeID) {
  22129. case Light.LIGHTTYPEID_POINTLIGHT:
  22130. case Light.LIGHTTYPEID_SPOTLIGHT:
  22131. switch (photometricMode) {
  22132. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22133. photometricScale = 1.0 / (4.0 * Math.PI);
  22134. break;
  22135. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22136. photometricScale = 1.0;
  22137. break;
  22138. case Light.INTENSITYMODE_LUMINANCE:
  22139. photometricScale = this.radius * this.radius;
  22140. break;
  22141. }
  22142. break;
  22143. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22144. switch (photometricMode) {
  22145. case Light.INTENSITYMODE_ILLUMINANCE:
  22146. photometricScale = 1.0;
  22147. break;
  22148. case Light.INTENSITYMODE_LUMINANCE:
  22149. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22150. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22151. var apexAngleRadians = this.radius;
  22152. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22153. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22154. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22155. photometricScale = solidAngle;
  22156. break;
  22157. }
  22158. break;
  22159. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22160. // No fall off in hemisperic light.
  22161. photometricScale = 1.0;
  22162. break;
  22163. }
  22164. return photometricScale;
  22165. };
  22166. /**
  22167. * Reorder the light in the scene according to their defined priority.
  22168. * @hidden Internal Use Only
  22169. */
  22170. Light.prototype._reorderLightsInScene = function () {
  22171. var scene = this.getScene();
  22172. if (this._renderPriority != 0) {
  22173. scene.requireLightSorting = true;
  22174. }
  22175. this.getScene().sortLightsByPriority();
  22176. };
  22177. //lightmapMode Consts
  22178. Light._LIGHTMAP_DEFAULT = 0;
  22179. Light._LIGHTMAP_SPECULAR = 1;
  22180. Light._LIGHTMAP_SHADOWSONLY = 2;
  22181. // Intensity Mode Consts
  22182. Light._INTENSITYMODE_AUTOMATIC = 0;
  22183. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22184. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22185. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22186. Light._INTENSITYMODE_LUMINANCE = 4;
  22187. // Light types ids const.
  22188. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22189. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22190. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22191. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22192. __decorate([
  22193. BABYLON.serializeAsColor3()
  22194. ], Light.prototype, "diffuse", void 0);
  22195. __decorate([
  22196. BABYLON.serializeAsColor3()
  22197. ], Light.prototype, "specular", void 0);
  22198. __decorate([
  22199. BABYLON.serialize()
  22200. ], Light.prototype, "intensity", void 0);
  22201. __decorate([
  22202. BABYLON.serialize()
  22203. ], Light.prototype, "range", void 0);
  22204. __decorate([
  22205. BABYLON.serialize()
  22206. ], Light.prototype, "intensityMode", null);
  22207. __decorate([
  22208. BABYLON.serialize()
  22209. ], Light.prototype, "radius", null);
  22210. __decorate([
  22211. BABYLON.serialize()
  22212. ], Light.prototype, "_renderPriority", void 0);
  22213. __decorate([
  22214. BABYLON.expandToProperty("_reorderLightsInScene")
  22215. ], Light.prototype, "renderPriority", void 0);
  22216. __decorate([
  22217. BABYLON.serialize("shadowEnabled")
  22218. ], Light.prototype, "_shadowEnabled", void 0);
  22219. __decorate([
  22220. BABYLON.serialize("excludeWithLayerMask")
  22221. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22222. __decorate([
  22223. BABYLON.serialize("includeOnlyWithLayerMask")
  22224. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22225. __decorate([
  22226. BABYLON.serialize("lightmapMode")
  22227. ], Light.prototype, "_lightmapMode", void 0);
  22228. return Light;
  22229. }(BABYLON.Node));
  22230. BABYLON.Light = Light;
  22231. })(BABYLON || (BABYLON = {}));
  22232. //# sourceMappingURL=babylon.light.js.map
  22233. var BABYLON;
  22234. (function (BABYLON) {
  22235. var Camera = /** @class */ (function (_super) {
  22236. __extends(Camera, _super);
  22237. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22238. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22239. var _this = _super.call(this, name, scene) || this;
  22240. /**
  22241. * The vector the camera should consider as up.
  22242. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22243. */
  22244. _this.upVector = BABYLON.Vector3.Up();
  22245. _this.orthoLeft = null;
  22246. _this.orthoRight = null;
  22247. _this.orthoBottom = null;
  22248. _this.orthoTop = null;
  22249. /**
  22250. * FOV is set in Radians. (default is 0.8)
  22251. */
  22252. _this.fov = 0.8;
  22253. _this.minZ = 1;
  22254. _this.maxZ = 10000.0;
  22255. _this.inertia = 0.9;
  22256. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22257. _this.isIntermediate = false;
  22258. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22259. /**
  22260. * Restricts the camera to viewing objects with the same layerMask.
  22261. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22262. */
  22263. _this.layerMask = 0x0FFFFFFF;
  22264. /**
  22265. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22266. */
  22267. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22268. // Camera rig members
  22269. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22270. _this._rigCameras = new Array();
  22271. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22272. _this._skipRendering = false;
  22273. _this.customRenderTargets = new Array();
  22274. // Observables
  22275. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22276. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22277. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22278. _this.onRestoreStateObservable = new BABYLON.Observable();
  22279. // Cache
  22280. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22281. _this._projectionMatrix = new BABYLON.Matrix();
  22282. _this._doNotComputeProjectionMatrix = false;
  22283. _this._worldMatrix = BABYLON.Matrix.Identity();
  22284. _this._postProcesses = new Array();
  22285. _this._transformMatrix = BABYLON.Matrix.Zero();
  22286. _this._activeMeshes = new BABYLON.SmartArray(256);
  22287. _this._globalPosition = BABYLON.Vector3.Zero();
  22288. _this._refreshFrustumPlanes = true;
  22289. _this.getScene().addCamera(_this);
  22290. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22291. _this.getScene().activeCamera = _this;
  22292. }
  22293. _this.position = position;
  22294. return _this;
  22295. }
  22296. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22297. get: function () {
  22298. return Camera._PERSPECTIVE_CAMERA;
  22299. },
  22300. enumerable: true,
  22301. configurable: true
  22302. });
  22303. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22304. get: function () {
  22305. return Camera._ORTHOGRAPHIC_CAMERA;
  22306. },
  22307. enumerable: true,
  22308. configurable: true
  22309. });
  22310. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22311. /**
  22312. * This is the default FOV mode for perspective cameras.
  22313. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22314. *
  22315. */
  22316. get: function () {
  22317. return Camera._FOVMODE_VERTICAL_FIXED;
  22318. },
  22319. enumerable: true,
  22320. configurable: true
  22321. });
  22322. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22323. /**
  22324. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22325. *
  22326. */
  22327. get: function () {
  22328. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22329. },
  22330. enumerable: true,
  22331. configurable: true
  22332. });
  22333. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22334. get: function () {
  22335. return Camera._RIG_MODE_NONE;
  22336. },
  22337. enumerable: true,
  22338. configurable: true
  22339. });
  22340. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22341. get: function () {
  22342. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22343. },
  22344. enumerable: true,
  22345. configurable: true
  22346. });
  22347. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22348. get: function () {
  22349. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22350. },
  22351. enumerable: true,
  22352. configurable: true
  22353. });
  22354. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22355. get: function () {
  22356. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22357. },
  22358. enumerable: true,
  22359. configurable: true
  22360. });
  22361. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22362. get: function () {
  22363. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22364. },
  22365. enumerable: true,
  22366. configurable: true
  22367. });
  22368. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22369. get: function () {
  22370. return Camera._RIG_MODE_VR;
  22371. },
  22372. enumerable: true,
  22373. configurable: true
  22374. });
  22375. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22376. get: function () {
  22377. return Camera._RIG_MODE_WEBVR;
  22378. },
  22379. enumerable: true,
  22380. configurable: true
  22381. });
  22382. /**
  22383. * Store current camera state (fov, position, etc..)
  22384. */
  22385. Camera.prototype.storeState = function () {
  22386. this._stateStored = true;
  22387. this._storedFov = this.fov;
  22388. return this;
  22389. };
  22390. /**
  22391. * Restores the camera state values if it has been stored. You must call storeState() first
  22392. */
  22393. Camera.prototype._restoreStateValues = function () {
  22394. if (!this._stateStored) {
  22395. return false;
  22396. }
  22397. this.fov = this._storedFov;
  22398. return true;
  22399. };
  22400. /**
  22401. * Restored camera state. You must call storeState() first
  22402. */
  22403. Camera.prototype.restoreState = function () {
  22404. if (this._restoreStateValues()) {
  22405. this.onRestoreStateObservable.notifyObservers(this);
  22406. return true;
  22407. }
  22408. return false;
  22409. };
  22410. Camera.prototype.getClassName = function () {
  22411. return "Camera";
  22412. };
  22413. /**
  22414. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22415. */
  22416. Camera.prototype.toString = function (fullDetails) {
  22417. var ret = "Name: " + this.name;
  22418. ret += ", type: " + this.getClassName();
  22419. if (this.animations) {
  22420. for (var i = 0; i < this.animations.length; i++) {
  22421. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22422. }
  22423. }
  22424. if (fullDetails) {
  22425. }
  22426. return ret;
  22427. };
  22428. Object.defineProperty(Camera.prototype, "globalPosition", {
  22429. get: function () {
  22430. return this._globalPosition;
  22431. },
  22432. enumerable: true,
  22433. configurable: true
  22434. });
  22435. Camera.prototype.getActiveMeshes = function () {
  22436. return this._activeMeshes;
  22437. };
  22438. Camera.prototype.isActiveMesh = function (mesh) {
  22439. return (this._activeMeshes.indexOf(mesh) !== -1);
  22440. };
  22441. /**
  22442. * Is this camera ready to be used/rendered
  22443. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22444. * @return true if the camera is ready
  22445. */
  22446. Camera.prototype.isReady = function (completeCheck) {
  22447. if (completeCheck === void 0) { completeCheck = false; }
  22448. if (completeCheck) {
  22449. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22450. var pp = _a[_i];
  22451. if (pp && !pp.isReady()) {
  22452. return false;
  22453. }
  22454. }
  22455. }
  22456. return _super.prototype.isReady.call(this, completeCheck);
  22457. };
  22458. //Cache
  22459. Camera.prototype._initCache = function () {
  22460. _super.prototype._initCache.call(this);
  22461. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22462. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22463. this._cache.mode = undefined;
  22464. this._cache.minZ = undefined;
  22465. this._cache.maxZ = undefined;
  22466. this._cache.fov = undefined;
  22467. this._cache.fovMode = undefined;
  22468. this._cache.aspectRatio = undefined;
  22469. this._cache.orthoLeft = undefined;
  22470. this._cache.orthoRight = undefined;
  22471. this._cache.orthoBottom = undefined;
  22472. this._cache.orthoTop = undefined;
  22473. this._cache.renderWidth = undefined;
  22474. this._cache.renderHeight = undefined;
  22475. };
  22476. Camera.prototype._updateCache = function (ignoreParentClass) {
  22477. if (!ignoreParentClass) {
  22478. _super.prototype._updateCache.call(this);
  22479. }
  22480. this._cache.position.copyFrom(this.position);
  22481. this._cache.upVector.copyFrom(this.upVector);
  22482. };
  22483. // Synchronized
  22484. Camera.prototype._isSynchronized = function () {
  22485. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22486. };
  22487. Camera.prototype._isSynchronizedViewMatrix = function () {
  22488. if (!_super.prototype._isSynchronized.call(this))
  22489. return false;
  22490. return this._cache.position.equals(this.position)
  22491. && this._cache.upVector.equals(this.upVector)
  22492. && this.isSynchronizedWithParent();
  22493. };
  22494. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22495. var check = this._cache.mode === this.mode
  22496. && this._cache.minZ === this.minZ
  22497. && this._cache.maxZ === this.maxZ;
  22498. if (!check) {
  22499. return false;
  22500. }
  22501. var engine = this.getEngine();
  22502. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22503. check = this._cache.fov === this.fov
  22504. && this._cache.fovMode === this.fovMode
  22505. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22506. }
  22507. else {
  22508. check = this._cache.orthoLeft === this.orthoLeft
  22509. && this._cache.orthoRight === this.orthoRight
  22510. && this._cache.orthoBottom === this.orthoBottom
  22511. && this._cache.orthoTop === this.orthoTop
  22512. && this._cache.renderWidth === engine.getRenderWidth()
  22513. && this._cache.renderHeight === engine.getRenderHeight();
  22514. }
  22515. return check;
  22516. };
  22517. // Controls
  22518. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22519. };
  22520. Camera.prototype.detachControl = function (element) {
  22521. };
  22522. Camera.prototype.update = function () {
  22523. this._checkInputs();
  22524. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22525. this._updateRigCameras();
  22526. }
  22527. };
  22528. Camera.prototype._checkInputs = function () {
  22529. this.onAfterCheckInputsObservable.notifyObservers(this);
  22530. };
  22531. Object.defineProperty(Camera.prototype, "rigCameras", {
  22532. get: function () {
  22533. return this._rigCameras;
  22534. },
  22535. enumerable: true,
  22536. configurable: true
  22537. });
  22538. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22539. get: function () {
  22540. return this._rigPostProcess;
  22541. },
  22542. enumerable: true,
  22543. configurable: true
  22544. });
  22545. /**
  22546. * Internal, gets the first post proces.
  22547. * @returns the first post process to be run on this camera.
  22548. */
  22549. Camera.prototype._getFirstPostProcess = function () {
  22550. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22551. if (this._postProcesses[ppIndex] !== null) {
  22552. return this._postProcesses[ppIndex];
  22553. }
  22554. }
  22555. return null;
  22556. };
  22557. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22558. // invalidate framebuffer
  22559. var firstPostProcess = this._getFirstPostProcess();
  22560. if (firstPostProcess) {
  22561. firstPostProcess.markTextureDirty();
  22562. }
  22563. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22564. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22565. var cam = this._rigCameras[i];
  22566. var rigPostProcess = cam._rigPostProcess;
  22567. // for VR rig, there does not have to be a post process
  22568. if (rigPostProcess) {
  22569. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22570. if (isPass) {
  22571. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22572. cam.isIntermediate = this._postProcesses.length === 0;
  22573. }
  22574. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22575. rigPostProcess.markTextureDirty();
  22576. }
  22577. else {
  22578. cam._postProcesses = this._postProcesses.slice(0);
  22579. }
  22580. }
  22581. };
  22582. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22583. if (insertAt === void 0) { insertAt = null; }
  22584. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22585. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22586. return 0;
  22587. }
  22588. if (insertAt == null || insertAt < 0) {
  22589. this._postProcesses.push(postProcess);
  22590. }
  22591. else if (this._postProcesses[insertAt] === null) {
  22592. this._postProcesses[insertAt] = postProcess;
  22593. }
  22594. else {
  22595. this._postProcesses.splice(insertAt, 0, postProcess);
  22596. }
  22597. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22598. return this._postProcesses.indexOf(postProcess);
  22599. };
  22600. Camera.prototype.detachPostProcess = function (postProcess) {
  22601. var idx = this._postProcesses.indexOf(postProcess);
  22602. if (idx !== -1) {
  22603. this._postProcesses[idx] = null;
  22604. }
  22605. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22606. };
  22607. Camera.prototype.getWorldMatrix = function () {
  22608. if (this._isSynchronizedViewMatrix()) {
  22609. return this._worldMatrix;
  22610. }
  22611. // Getting the the view matrix will also compute the world matrix.
  22612. this.getViewMatrix();
  22613. return this._worldMatrix;
  22614. };
  22615. Camera.prototype._getViewMatrix = function () {
  22616. return BABYLON.Matrix.Identity();
  22617. };
  22618. Camera.prototype.getViewMatrix = function (force) {
  22619. if (!force && this._isSynchronizedViewMatrix()) {
  22620. return this._computedViewMatrix;
  22621. }
  22622. this.updateCache();
  22623. this._computedViewMatrix = this._getViewMatrix();
  22624. this._currentRenderId = this.getScene().getRenderId();
  22625. this._childRenderId = this._currentRenderId;
  22626. this._refreshFrustumPlanes = true;
  22627. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22628. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22629. }
  22630. this.onViewMatrixChangedObservable.notifyObservers(this);
  22631. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22632. return this._computedViewMatrix;
  22633. };
  22634. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22635. this._doNotComputeProjectionMatrix = true;
  22636. if (projection !== undefined) {
  22637. this._projectionMatrix = projection;
  22638. }
  22639. };
  22640. ;
  22641. Camera.prototype.unfreezeProjectionMatrix = function () {
  22642. this._doNotComputeProjectionMatrix = false;
  22643. };
  22644. ;
  22645. Camera.prototype.getProjectionMatrix = function (force) {
  22646. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22647. return this._projectionMatrix;
  22648. }
  22649. // Cache
  22650. this._cache.mode = this.mode;
  22651. this._cache.minZ = this.minZ;
  22652. this._cache.maxZ = this.maxZ;
  22653. // Matrix
  22654. this._refreshFrustumPlanes = true;
  22655. var engine = this.getEngine();
  22656. var scene = this.getScene();
  22657. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22658. this._cache.fov = this.fov;
  22659. this._cache.fovMode = this.fovMode;
  22660. this._cache.aspectRatio = engine.getAspectRatio(this);
  22661. if (this.minZ <= 0) {
  22662. this.minZ = 0.1;
  22663. }
  22664. if (scene.useRightHandedSystem) {
  22665. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22666. }
  22667. else {
  22668. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22669. }
  22670. }
  22671. else {
  22672. var halfWidth = engine.getRenderWidth() / 2.0;
  22673. var halfHeight = engine.getRenderHeight() / 2.0;
  22674. if (scene.useRightHandedSystem) {
  22675. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22676. }
  22677. else {
  22678. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22679. }
  22680. this._cache.orthoLeft = this.orthoLeft;
  22681. this._cache.orthoRight = this.orthoRight;
  22682. this._cache.orthoBottom = this.orthoBottom;
  22683. this._cache.orthoTop = this.orthoTop;
  22684. this._cache.renderWidth = engine.getRenderWidth();
  22685. this._cache.renderHeight = engine.getRenderHeight();
  22686. }
  22687. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22688. return this._projectionMatrix;
  22689. };
  22690. Camera.prototype.getTranformationMatrix = function () {
  22691. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22692. return this._transformMatrix;
  22693. };
  22694. Camera.prototype.updateFrustumPlanes = function () {
  22695. if (!this._refreshFrustumPlanes) {
  22696. return;
  22697. }
  22698. this.getTranformationMatrix();
  22699. if (!this._frustumPlanes) {
  22700. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22701. }
  22702. else {
  22703. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22704. }
  22705. this._refreshFrustumPlanes = false;
  22706. };
  22707. Camera.prototype.isInFrustum = function (target) {
  22708. this.updateFrustumPlanes();
  22709. return target.isInFrustum(this._frustumPlanes);
  22710. };
  22711. Camera.prototype.isCompletelyInFrustum = function (target) {
  22712. this.updateFrustumPlanes();
  22713. return target.isCompletelyInFrustum(this._frustumPlanes);
  22714. };
  22715. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22716. if (length === void 0) { length = 100; }
  22717. if (!transform) {
  22718. transform = this.getWorldMatrix();
  22719. }
  22720. if (!origin) {
  22721. origin = this.position;
  22722. }
  22723. var forward = new BABYLON.Vector3(0, 0, 1);
  22724. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22725. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22726. return new BABYLON.Ray(origin, direction, length);
  22727. };
  22728. /**
  22729. * Releases resources associated with this node.
  22730. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22731. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22732. */
  22733. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22734. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22735. // Observables
  22736. this.onViewMatrixChangedObservable.clear();
  22737. this.onProjectionMatrixChangedObservable.clear();
  22738. this.onAfterCheckInputsObservable.clear();
  22739. this.onRestoreStateObservable.clear();
  22740. // Inputs
  22741. if (this.inputs) {
  22742. this.inputs.clear();
  22743. }
  22744. // Animations
  22745. this.getScene().stopAnimation(this);
  22746. // Remove from scene
  22747. this.getScene().removeCamera(this);
  22748. while (this._rigCameras.length > 0) {
  22749. var camera = this._rigCameras.pop();
  22750. if (camera) {
  22751. camera.dispose();
  22752. }
  22753. }
  22754. // Postprocesses
  22755. if (this._rigPostProcess) {
  22756. this._rigPostProcess.dispose(this);
  22757. this._rigPostProcess = null;
  22758. this._postProcesses = [];
  22759. }
  22760. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22761. this._rigPostProcess = null;
  22762. this._postProcesses = [];
  22763. }
  22764. else {
  22765. var i = this._postProcesses.length;
  22766. while (--i >= 0) {
  22767. var postProcess = this._postProcesses[i];
  22768. if (postProcess) {
  22769. postProcess.dispose(this);
  22770. }
  22771. }
  22772. }
  22773. // Render targets
  22774. var i = this.customRenderTargets.length;
  22775. while (--i >= 0) {
  22776. this.customRenderTargets[i].dispose();
  22777. }
  22778. this.customRenderTargets = [];
  22779. // Active Meshes
  22780. this._activeMeshes.dispose();
  22781. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22782. };
  22783. Object.defineProperty(Camera.prototype, "leftCamera", {
  22784. // ---- Camera rigs section ----
  22785. get: function () {
  22786. if (this._rigCameras.length < 1) {
  22787. return null;
  22788. }
  22789. return this._rigCameras[0];
  22790. },
  22791. enumerable: true,
  22792. configurable: true
  22793. });
  22794. Object.defineProperty(Camera.prototype, "rightCamera", {
  22795. get: function () {
  22796. if (this._rigCameras.length < 2) {
  22797. return null;
  22798. }
  22799. return this._rigCameras[1];
  22800. },
  22801. enumerable: true,
  22802. configurable: true
  22803. });
  22804. Camera.prototype.getLeftTarget = function () {
  22805. if (this._rigCameras.length < 1) {
  22806. return null;
  22807. }
  22808. return this._rigCameras[0].getTarget();
  22809. };
  22810. Camera.prototype.getRightTarget = function () {
  22811. if (this._rigCameras.length < 2) {
  22812. return null;
  22813. }
  22814. return this._rigCameras[1].getTarget();
  22815. };
  22816. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22817. if (this.cameraRigMode === mode) {
  22818. return;
  22819. }
  22820. while (this._rigCameras.length > 0) {
  22821. var camera = this._rigCameras.pop();
  22822. if (camera) {
  22823. camera.dispose();
  22824. }
  22825. }
  22826. this.cameraRigMode = mode;
  22827. this._cameraRigParams = {};
  22828. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22829. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22830. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22831. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22832. // create the rig cameras, unless none
  22833. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22834. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22835. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22836. if (leftCamera && rightCamera) {
  22837. this._rigCameras.push(leftCamera);
  22838. this._rigCameras.push(rightCamera);
  22839. }
  22840. }
  22841. switch (this.cameraRigMode) {
  22842. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22843. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22844. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22845. break;
  22846. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22847. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22848. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22849. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22850. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22851. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22852. break;
  22853. case Camera.RIG_MODE_VR:
  22854. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22855. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22856. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22857. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22858. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22859. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22860. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22861. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22862. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22863. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22864. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22865. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22866. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22867. if (metrics.compensateDistortion) {
  22868. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22869. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22870. }
  22871. break;
  22872. case Camera.RIG_MODE_WEBVR:
  22873. if (rigParams.vrDisplay) {
  22874. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22875. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22876. //Left eye
  22877. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22878. this._rigCameras[0].setCameraRigParameter("left", true);
  22879. //leaving this for future reference
  22880. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22881. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22882. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22883. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22884. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22885. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22886. this._rigCameras[0].parent = this;
  22887. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22888. //Right eye
  22889. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22890. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22891. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22892. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22893. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22894. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22895. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22896. this._rigCameras[1].parent = this;
  22897. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22898. if (Camera.UseAlternateWebVRRendering) {
  22899. this._rigCameras[1]._skipRendering = true;
  22900. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22901. }
  22902. }
  22903. break;
  22904. }
  22905. this._cascadePostProcessesToRigCams();
  22906. this.update();
  22907. };
  22908. Camera.prototype._getVRProjectionMatrix = function () {
  22909. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22910. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22911. return this._projectionMatrix;
  22912. };
  22913. Camera.prototype._updateCameraRotationMatrix = function () {
  22914. //Here for WebVR
  22915. };
  22916. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22917. //Here for WebVR
  22918. };
  22919. /**
  22920. * This function MUST be overwritten by the different WebVR cameras available.
  22921. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22922. */
  22923. Camera.prototype._getWebVRProjectionMatrix = function () {
  22924. return BABYLON.Matrix.Identity();
  22925. };
  22926. /**
  22927. * This function MUST be overwritten by the different WebVR cameras available.
  22928. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22929. */
  22930. Camera.prototype._getWebVRViewMatrix = function () {
  22931. return BABYLON.Matrix.Identity();
  22932. };
  22933. Camera.prototype.setCameraRigParameter = function (name, value) {
  22934. if (!this._cameraRigParams) {
  22935. this._cameraRigParams = {};
  22936. }
  22937. this._cameraRigParams[name] = value;
  22938. //provisionnally:
  22939. if (name === "interaxialDistance") {
  22940. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22941. }
  22942. };
  22943. /**
  22944. * needs to be overridden by children so sub has required properties to be copied
  22945. */
  22946. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22947. return null;
  22948. };
  22949. /**
  22950. * May need to be overridden by children
  22951. */
  22952. Camera.prototype._updateRigCameras = function () {
  22953. for (var i = 0; i < this._rigCameras.length; i++) {
  22954. this._rigCameras[i].minZ = this.minZ;
  22955. this._rigCameras[i].maxZ = this.maxZ;
  22956. this._rigCameras[i].fov = this.fov;
  22957. }
  22958. // only update viewport when ANAGLYPH
  22959. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22960. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22961. }
  22962. };
  22963. Camera.prototype._setupInputs = function () {
  22964. };
  22965. Camera.prototype.serialize = function () {
  22966. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22967. // Type
  22968. serializationObject.type = this.getClassName();
  22969. // Parent
  22970. if (this.parent) {
  22971. serializationObject.parentId = this.parent.id;
  22972. }
  22973. if (this.inputs) {
  22974. this.inputs.serialize(serializationObject);
  22975. }
  22976. // Animations
  22977. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22978. serializationObject.ranges = this.serializeAnimationRanges();
  22979. return serializationObject;
  22980. };
  22981. Camera.prototype.clone = function (name) {
  22982. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22983. };
  22984. Camera.prototype.getDirection = function (localAxis) {
  22985. var result = BABYLON.Vector3.Zero();
  22986. this.getDirectionToRef(localAxis, result);
  22987. return result;
  22988. };
  22989. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22990. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22991. };
  22992. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22993. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22994. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22995. switch (type) {
  22996. case "ArcRotateCamera":
  22997. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22998. case "DeviceOrientationCamera":
  22999. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  23000. case "FollowCamera":
  23001. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  23002. case "ArcFollowCamera":
  23003. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  23004. case "GamepadCamera":
  23005. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23006. case "TouchCamera":
  23007. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  23008. case "VirtualJoysticksCamera":
  23009. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  23010. case "WebVRFreeCamera":
  23011. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23012. case "WebVRGamepadCamera":
  23013. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23014. case "VRDeviceOrientationFreeCamera":
  23015. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23016. case "VRDeviceOrientationGamepadCamera":
  23017. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23018. case "AnaglyphArcRotateCamera":
  23019. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23020. case "AnaglyphFreeCamera":
  23021. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23022. case "AnaglyphGamepadCamera":
  23023. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23024. case "AnaglyphUniversalCamera":
  23025. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23026. case "StereoscopicArcRotateCamera":
  23027. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23028. case "StereoscopicFreeCamera":
  23029. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23030. case "StereoscopicGamepadCamera":
  23031. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23032. case "StereoscopicUniversalCamera":
  23033. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23034. case "FreeCamera": // Forcing Universal here
  23035. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23036. default: // Universal Camera is the default value
  23037. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23038. }
  23039. };
  23040. Camera.prototype.computeWorldMatrix = function () {
  23041. return this.getWorldMatrix();
  23042. };
  23043. Camera.Parse = function (parsedCamera, scene) {
  23044. var type = parsedCamera.type;
  23045. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23046. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23047. // Parent
  23048. if (parsedCamera.parentId) {
  23049. camera._waitingParentId = parsedCamera.parentId;
  23050. }
  23051. //If camera has an input manager, let it parse inputs settings
  23052. if (camera.inputs) {
  23053. camera.inputs.parse(parsedCamera);
  23054. camera._setupInputs();
  23055. }
  23056. if (camera.setPosition) { // need to force position
  23057. camera.position.copyFromFloats(0, 0, 0);
  23058. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23059. }
  23060. // Target
  23061. if (parsedCamera.target) {
  23062. if (camera.setTarget) {
  23063. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23064. }
  23065. }
  23066. // Apply 3d rig, when found
  23067. if (parsedCamera.cameraRigMode) {
  23068. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23069. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23070. }
  23071. // Animations
  23072. if (parsedCamera.animations) {
  23073. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23074. var parsedAnimation = parsedCamera.animations[animationIndex];
  23075. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23076. }
  23077. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23078. }
  23079. if (parsedCamera.autoAnimate) {
  23080. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23081. }
  23082. return camera;
  23083. };
  23084. // Statics
  23085. Camera._PERSPECTIVE_CAMERA = 0;
  23086. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23087. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23088. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23089. Camera._RIG_MODE_NONE = 0;
  23090. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23091. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23092. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23093. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23094. Camera._RIG_MODE_VR = 20;
  23095. Camera._RIG_MODE_WEBVR = 21;
  23096. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23097. Camera.UseAlternateWebVRRendering = false;
  23098. __decorate([
  23099. BABYLON.serializeAsVector3()
  23100. ], Camera.prototype, "position", void 0);
  23101. __decorate([
  23102. BABYLON.serializeAsVector3()
  23103. ], Camera.prototype, "upVector", void 0);
  23104. __decorate([
  23105. BABYLON.serialize()
  23106. ], Camera.prototype, "orthoLeft", void 0);
  23107. __decorate([
  23108. BABYLON.serialize()
  23109. ], Camera.prototype, "orthoRight", void 0);
  23110. __decorate([
  23111. BABYLON.serialize()
  23112. ], Camera.prototype, "orthoBottom", void 0);
  23113. __decorate([
  23114. BABYLON.serialize()
  23115. ], Camera.prototype, "orthoTop", void 0);
  23116. __decorate([
  23117. BABYLON.serialize()
  23118. ], Camera.prototype, "fov", void 0);
  23119. __decorate([
  23120. BABYLON.serialize()
  23121. ], Camera.prototype, "minZ", void 0);
  23122. __decorate([
  23123. BABYLON.serialize()
  23124. ], Camera.prototype, "maxZ", void 0);
  23125. __decorate([
  23126. BABYLON.serialize()
  23127. ], Camera.prototype, "inertia", void 0);
  23128. __decorate([
  23129. BABYLON.serialize()
  23130. ], Camera.prototype, "mode", void 0);
  23131. __decorate([
  23132. BABYLON.serialize()
  23133. ], Camera.prototype, "layerMask", void 0);
  23134. __decorate([
  23135. BABYLON.serialize()
  23136. ], Camera.prototype, "fovMode", void 0);
  23137. __decorate([
  23138. BABYLON.serialize()
  23139. ], Camera.prototype, "cameraRigMode", void 0);
  23140. __decorate([
  23141. BABYLON.serialize()
  23142. ], Camera.prototype, "interaxialDistance", void 0);
  23143. __decorate([
  23144. BABYLON.serialize()
  23145. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23146. return Camera;
  23147. }(BABYLON.Node));
  23148. BABYLON.Camera = Camera;
  23149. })(BABYLON || (BABYLON = {}));
  23150. //# sourceMappingURL=babylon.camera.js.map
  23151. var BABYLON;
  23152. (function (BABYLON) {
  23153. var RenderingManager = /** @class */ (function () {
  23154. function RenderingManager(scene) {
  23155. this._renderingGroups = new Array();
  23156. this._autoClearDepthStencil = {};
  23157. this._customOpaqueSortCompareFn = {};
  23158. this._customAlphaTestSortCompareFn = {};
  23159. this._customTransparentSortCompareFn = {};
  23160. this._renderinGroupInfo = null;
  23161. this._scene = scene;
  23162. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23163. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23164. }
  23165. }
  23166. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23167. if (depth === void 0) { depth = true; }
  23168. if (stencil === void 0) { stencil = true; }
  23169. if (this._depthStencilBufferAlreadyCleaned) {
  23170. return;
  23171. }
  23172. this._scene.getEngine().clear(null, false, depth, stencil);
  23173. this._depthStencilBufferAlreadyCleaned = true;
  23174. };
  23175. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23176. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23177. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23178. var info = null;
  23179. if (observable) {
  23180. if (!this._renderinGroupInfo) {
  23181. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23182. }
  23183. info = this._renderinGroupInfo;
  23184. info.scene = this._scene;
  23185. info.camera = this._scene.activeCamera;
  23186. }
  23187. // Dispatch sprites
  23188. if (renderSprites) {
  23189. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23190. var manager = this._scene.spriteManagers[index];
  23191. this.dispatchSprites(manager);
  23192. }
  23193. }
  23194. // Render
  23195. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23196. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23197. var renderingGroup = this._renderingGroups[index];
  23198. if (!renderingGroup && !observable)
  23199. continue;
  23200. var renderingGroupMask = 0;
  23201. // Fire PRECLEAR stage
  23202. if (observable && info) {
  23203. renderingGroupMask = Math.pow(2, index);
  23204. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23205. info.renderingGroupId = index;
  23206. observable.notifyObservers(info, renderingGroupMask);
  23207. }
  23208. // Clear depth/stencil if needed
  23209. if (RenderingManager.AUTOCLEAR) {
  23210. var autoClear = this._autoClearDepthStencil[index];
  23211. if (autoClear && autoClear.autoClear) {
  23212. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23213. }
  23214. }
  23215. if (observable && info) {
  23216. // Fire PREOPAQUE stage
  23217. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23218. observable.notifyObservers(info, renderingGroupMask);
  23219. // Fire PRETRANSPARENT stage
  23220. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23221. observable.notifyObservers(info, renderingGroupMask);
  23222. }
  23223. if (renderingGroup)
  23224. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23225. // Fire POSTTRANSPARENT stage
  23226. if (observable && info) {
  23227. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23228. observable.notifyObservers(info, renderingGroupMask);
  23229. }
  23230. }
  23231. };
  23232. RenderingManager.prototype.reset = function () {
  23233. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23234. var renderingGroup = this._renderingGroups[index];
  23235. if (renderingGroup) {
  23236. renderingGroup.prepare();
  23237. }
  23238. }
  23239. };
  23240. RenderingManager.prototype.dispose = function () {
  23241. this.freeRenderingGroups();
  23242. this._renderingGroups.length = 0;
  23243. };
  23244. /**
  23245. * Clear the info related to rendering groups preventing retention points during dispose.
  23246. */
  23247. RenderingManager.prototype.freeRenderingGroups = function () {
  23248. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23249. var renderingGroup = this._renderingGroups[index];
  23250. if (renderingGroup) {
  23251. renderingGroup.dispose();
  23252. }
  23253. }
  23254. };
  23255. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23256. if (this._renderingGroups[renderingGroupId] === undefined) {
  23257. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23258. }
  23259. };
  23260. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23261. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23262. this._prepareRenderingGroup(renderingGroupId);
  23263. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23264. };
  23265. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23266. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23267. this._prepareRenderingGroup(renderingGroupId);
  23268. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23269. };
  23270. /**
  23271. * @param subMesh The submesh to dispatch
  23272. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23273. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23274. */
  23275. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23276. if (mesh === undefined) {
  23277. mesh = subMesh.getMesh();
  23278. }
  23279. var renderingGroupId = mesh.renderingGroupId || 0;
  23280. this._prepareRenderingGroup(renderingGroupId);
  23281. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23282. };
  23283. /**
  23284. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23285. * This allowed control for front to back rendering or reversly depending of the special needs.
  23286. *
  23287. * @param renderingGroupId The rendering group id corresponding to its index
  23288. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23289. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23290. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23291. */
  23292. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23293. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23294. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23295. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23296. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23297. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23298. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23299. if (this._renderingGroups[renderingGroupId]) {
  23300. var group = this._renderingGroups[renderingGroupId];
  23301. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23302. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23303. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23304. }
  23305. };
  23306. /**
  23307. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23308. *
  23309. * @param renderingGroupId The rendering group id corresponding to its index
  23310. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23311. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23312. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23313. */
  23314. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23315. if (depth === void 0) { depth = true; }
  23316. if (stencil === void 0) { stencil = true; }
  23317. this._autoClearDepthStencil[renderingGroupId] = {
  23318. autoClear: autoClearDepthStencil,
  23319. depth: depth,
  23320. stencil: stencil
  23321. };
  23322. };
  23323. /**
  23324. * The max id used for rendering groups (not included)
  23325. */
  23326. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23327. /**
  23328. * The min id used for rendering groups (included)
  23329. */
  23330. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23331. /**
  23332. * Used to globally prevent autoclearing scenes.
  23333. */
  23334. RenderingManager.AUTOCLEAR = true;
  23335. return RenderingManager;
  23336. }());
  23337. BABYLON.RenderingManager = RenderingManager;
  23338. })(BABYLON || (BABYLON = {}));
  23339. //# sourceMappingURL=babylon.renderingManager.js.map
  23340. var BABYLON;
  23341. (function (BABYLON) {
  23342. var RenderingGroup = /** @class */ (function () {
  23343. /**
  23344. * Creates a new rendering group.
  23345. * @param index The rendering group index
  23346. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23347. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23348. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23349. */
  23350. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23351. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23352. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23353. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23354. this.index = index;
  23355. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23356. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23357. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23358. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23359. this._particleSystems = new BABYLON.SmartArray(256);
  23360. this._spriteManagers = new BABYLON.SmartArray(256);
  23361. this._edgesRenderers = new BABYLON.SmartArray(16);
  23362. this._scene = scene;
  23363. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23364. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23365. this.transparentSortCompareFn = transparentSortCompareFn;
  23366. }
  23367. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23368. /**
  23369. * Set the opaque sort comparison function.
  23370. * If null the sub meshes will be render in the order they were created
  23371. */
  23372. set: function (value) {
  23373. this._opaqueSortCompareFn = value;
  23374. if (value) {
  23375. this._renderOpaque = this.renderOpaqueSorted;
  23376. }
  23377. else {
  23378. this._renderOpaque = RenderingGroup.renderUnsorted;
  23379. }
  23380. },
  23381. enumerable: true,
  23382. configurable: true
  23383. });
  23384. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23385. /**
  23386. * Set the alpha test sort comparison function.
  23387. * If null the sub meshes will be render in the order they were created
  23388. */
  23389. set: function (value) {
  23390. this._alphaTestSortCompareFn = value;
  23391. if (value) {
  23392. this._renderAlphaTest = this.renderAlphaTestSorted;
  23393. }
  23394. else {
  23395. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23396. }
  23397. },
  23398. enumerable: true,
  23399. configurable: true
  23400. });
  23401. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23402. /**
  23403. * Set the transparent sort comparison function.
  23404. * If null the sub meshes will be render in the order they were created
  23405. */
  23406. set: function (value) {
  23407. if (value) {
  23408. this._transparentSortCompareFn = value;
  23409. }
  23410. else {
  23411. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23412. }
  23413. this._renderTransparent = this.renderTransparentSorted;
  23414. },
  23415. enumerable: true,
  23416. configurable: true
  23417. });
  23418. /**
  23419. * Render all the sub meshes contained in the group.
  23420. * @param customRenderFunction Used to override the default render behaviour of the group.
  23421. * @returns true if rendered some submeshes.
  23422. */
  23423. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23424. if (customRenderFunction) {
  23425. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23426. return;
  23427. }
  23428. var engine = this._scene.getEngine();
  23429. // Depth only
  23430. if (this._depthOnlySubMeshes.length !== 0) {
  23431. engine.setColorWrite(false);
  23432. this._renderAlphaTest(this._depthOnlySubMeshes);
  23433. engine.setColorWrite(true);
  23434. }
  23435. // Opaque
  23436. if (this._opaqueSubMeshes.length !== 0) {
  23437. this._renderOpaque(this._opaqueSubMeshes);
  23438. }
  23439. // Alpha test
  23440. if (this._alphaTestSubMeshes.length !== 0) {
  23441. this._renderAlphaTest(this._alphaTestSubMeshes);
  23442. }
  23443. var stencilState = engine.getStencilBuffer();
  23444. engine.setStencilBuffer(false);
  23445. // Sprites
  23446. if (renderSprites) {
  23447. this._renderSprites();
  23448. }
  23449. // Particles
  23450. if (renderParticles) {
  23451. this._renderParticles(activeMeshes);
  23452. }
  23453. if (this.onBeforeTransparentRendering) {
  23454. this.onBeforeTransparentRendering();
  23455. }
  23456. // Transparent
  23457. if (this._transparentSubMeshes.length !== 0) {
  23458. this._renderTransparent(this._transparentSubMeshes);
  23459. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23460. }
  23461. // Set back stencil to false in case it changes before the edge renderer.
  23462. engine.setStencilBuffer(false);
  23463. // Edges
  23464. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23465. this._edgesRenderers.data[edgesRendererIndex].render();
  23466. }
  23467. // Restore Stencil state.
  23468. engine.setStencilBuffer(stencilState);
  23469. };
  23470. /**
  23471. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23472. * @param subMeshes The submeshes to render
  23473. */
  23474. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23475. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23476. };
  23477. /**
  23478. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23479. * @param subMeshes The submeshes to render
  23480. */
  23481. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23482. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23483. };
  23484. /**
  23485. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23486. * @param subMeshes The submeshes to render
  23487. */
  23488. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23489. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23490. };
  23491. /**
  23492. * Renders the submeshes in a specified order.
  23493. * @param subMeshes The submeshes to sort before render
  23494. * @param sortCompareFn The comparison function use to sort
  23495. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23496. * @param transparent Specifies to activate blending if true
  23497. */
  23498. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23499. var subIndex = 0;
  23500. var subMesh;
  23501. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23502. for (; subIndex < subMeshes.length; subIndex++) {
  23503. subMesh = subMeshes.data[subIndex];
  23504. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23505. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23506. }
  23507. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23508. if (sortCompareFn) {
  23509. sortedArray.sort(sortCompareFn);
  23510. }
  23511. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23512. subMesh = sortedArray[subIndex];
  23513. if (transparent) {
  23514. var material = subMesh.getMaterial();
  23515. if (material && material.needDepthPrePass) {
  23516. var engine = material.getScene().getEngine();
  23517. engine.setColorWrite(false);
  23518. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23519. subMesh.render(false);
  23520. engine.setColorWrite(true);
  23521. }
  23522. }
  23523. subMesh.render(transparent);
  23524. }
  23525. };
  23526. /**
  23527. * Renders the submeshes in the order they were dispatched (no sort applied).
  23528. * @param subMeshes The submeshes to render
  23529. */
  23530. RenderingGroup.renderUnsorted = function (subMeshes) {
  23531. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23532. var submesh = subMeshes.data[subIndex];
  23533. submesh.render(false);
  23534. }
  23535. };
  23536. /**
  23537. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23538. * are rendered back to front if in the same alpha index.
  23539. *
  23540. * @param a The first submesh
  23541. * @param b The second submesh
  23542. * @returns The result of the comparison
  23543. */
  23544. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23545. // Alpha index first
  23546. if (a._alphaIndex > b._alphaIndex) {
  23547. return 1;
  23548. }
  23549. if (a._alphaIndex < b._alphaIndex) {
  23550. return -1;
  23551. }
  23552. // Then distance to camera
  23553. return RenderingGroup.backToFrontSortCompare(a, b);
  23554. };
  23555. /**
  23556. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23557. * are rendered back to front.
  23558. *
  23559. * @param a The first submesh
  23560. * @param b The second submesh
  23561. * @returns The result of the comparison
  23562. */
  23563. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23564. // Then distance to camera
  23565. if (a._distanceToCamera < b._distanceToCamera) {
  23566. return 1;
  23567. }
  23568. if (a._distanceToCamera > b._distanceToCamera) {
  23569. return -1;
  23570. }
  23571. return 0;
  23572. };
  23573. /**
  23574. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23575. * are rendered front to back (prevent overdraw).
  23576. *
  23577. * @param a The first submesh
  23578. * @param b The second submesh
  23579. * @returns The result of the comparison
  23580. */
  23581. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23582. // Then distance to camera
  23583. if (a._distanceToCamera < b._distanceToCamera) {
  23584. return -1;
  23585. }
  23586. if (a._distanceToCamera > b._distanceToCamera) {
  23587. return 1;
  23588. }
  23589. return 0;
  23590. };
  23591. /**
  23592. * Resets the different lists of submeshes to prepare a new frame.
  23593. */
  23594. RenderingGroup.prototype.prepare = function () {
  23595. this._opaqueSubMeshes.reset();
  23596. this._transparentSubMeshes.reset();
  23597. this._alphaTestSubMeshes.reset();
  23598. this._depthOnlySubMeshes.reset();
  23599. this._particleSystems.reset();
  23600. this._spriteManagers.reset();
  23601. this._edgesRenderers.reset();
  23602. };
  23603. RenderingGroup.prototype.dispose = function () {
  23604. this._opaqueSubMeshes.dispose();
  23605. this._transparentSubMeshes.dispose();
  23606. this._alphaTestSubMeshes.dispose();
  23607. this._depthOnlySubMeshes.dispose();
  23608. this._particleSystems.dispose();
  23609. this._spriteManagers.dispose();
  23610. this._edgesRenderers.dispose();
  23611. };
  23612. /**
  23613. * Inserts the submesh in its correct queue depending on its material.
  23614. * @param subMesh The submesh to dispatch
  23615. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23616. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23617. */
  23618. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23619. // Get mesh and materials if not provided
  23620. if (mesh === undefined) {
  23621. mesh = subMesh.getMesh();
  23622. }
  23623. if (material === undefined) {
  23624. material = subMesh.getMaterial();
  23625. }
  23626. if (material === null || material === undefined) {
  23627. return;
  23628. }
  23629. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23630. this._transparentSubMeshes.push(subMesh);
  23631. }
  23632. else if (material.needAlphaTesting()) { // Alpha test
  23633. if (material.needDepthPrePass) {
  23634. this._depthOnlySubMeshes.push(subMesh);
  23635. }
  23636. this._alphaTestSubMeshes.push(subMesh);
  23637. }
  23638. else {
  23639. if (material.needDepthPrePass) {
  23640. this._depthOnlySubMeshes.push(subMesh);
  23641. }
  23642. this._opaqueSubMeshes.push(subMesh); // Opaque
  23643. }
  23644. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23645. this._edgesRenderers.push(mesh._edgesRenderer);
  23646. }
  23647. };
  23648. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23649. this._spriteManagers.push(spriteManager);
  23650. };
  23651. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23652. this._particleSystems.push(particleSystem);
  23653. };
  23654. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23655. if (this._particleSystems.length === 0) {
  23656. return;
  23657. }
  23658. // Particles
  23659. var activeCamera = this._scene.activeCamera;
  23660. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23661. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23662. var particleSystem = this._particleSystems.data[particleIndex];
  23663. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23664. continue;
  23665. }
  23666. var emitter = particleSystem.emitter;
  23667. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23668. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23669. }
  23670. }
  23671. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23672. };
  23673. RenderingGroup.prototype._renderSprites = function () {
  23674. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23675. return;
  23676. }
  23677. // Sprites
  23678. var activeCamera = this._scene.activeCamera;
  23679. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23680. for (var id = 0; id < this._spriteManagers.length; id++) {
  23681. var spriteManager = this._spriteManagers.data[id];
  23682. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23683. spriteManager.render();
  23684. }
  23685. }
  23686. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23687. };
  23688. return RenderingGroup;
  23689. }());
  23690. BABYLON.RenderingGroup = RenderingGroup;
  23691. })(BABYLON || (BABYLON = {}));
  23692. //# sourceMappingURL=babylon.renderingGroup.js.map
  23693. var BABYLON;
  23694. (function (BABYLON) {
  23695. /** @hidden */
  23696. var ClickInfo = /** @class */ (function () {
  23697. function ClickInfo() {
  23698. this._singleClick = false;
  23699. this._doubleClick = false;
  23700. this._hasSwiped = false;
  23701. this._ignore = false;
  23702. }
  23703. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23704. get: function () {
  23705. return this._singleClick;
  23706. },
  23707. set: function (b) {
  23708. this._singleClick = b;
  23709. },
  23710. enumerable: true,
  23711. configurable: true
  23712. });
  23713. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23714. get: function () {
  23715. return this._doubleClick;
  23716. },
  23717. set: function (b) {
  23718. this._doubleClick = b;
  23719. },
  23720. enumerable: true,
  23721. configurable: true
  23722. });
  23723. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23724. get: function () {
  23725. return this._hasSwiped;
  23726. },
  23727. set: function (b) {
  23728. this._hasSwiped = b;
  23729. },
  23730. enumerable: true,
  23731. configurable: true
  23732. });
  23733. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23734. get: function () {
  23735. return this._ignore;
  23736. },
  23737. set: function (b) {
  23738. this._ignore = b;
  23739. },
  23740. enumerable: true,
  23741. configurable: true
  23742. });
  23743. return ClickInfo;
  23744. }());
  23745. /**
  23746. * This class is used by the onRenderingGroupObservable
  23747. */
  23748. var RenderingGroupInfo = /** @class */ (function () {
  23749. function RenderingGroupInfo() {
  23750. }
  23751. /**
  23752. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23753. * This stage will be fired no matter what
  23754. */
  23755. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23756. /**
  23757. * Called before opaque object are rendered.
  23758. * This stage will be fired only if there's 3D Opaque content to render
  23759. */
  23760. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23761. /**
  23762. * Called after the opaque objects are rendered and before the transparent ones
  23763. * This stage will be fired only if there's 3D transparent content to render
  23764. */
  23765. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23766. /**
  23767. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23768. * This stage will be fired no matter what
  23769. */
  23770. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23771. return RenderingGroupInfo;
  23772. }());
  23773. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23774. /**
  23775. * Represents a scene to be rendered by the engine.
  23776. * @see http://doc.babylonjs.com/features/scene
  23777. */
  23778. var Scene = /** @class */ (function () {
  23779. /**
  23780. * Creates a new Scene
  23781. * @param engine defines the engine to use to render this scene
  23782. */
  23783. function Scene(engine) {
  23784. // Members
  23785. /**
  23786. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23787. */
  23788. this.autoClear = true;
  23789. /**
  23790. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23791. */
  23792. this.autoClearDepthAndStencil = true;
  23793. /**
  23794. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23795. */
  23796. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23797. /**
  23798. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23799. */
  23800. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23801. this._forceWireframe = false;
  23802. this._forcePointsCloud = false;
  23803. /**
  23804. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23805. */
  23806. this.forceShowBoundingBoxes = false;
  23807. /**
  23808. * Gets or sets a boolean indicating if animations are enabled
  23809. */
  23810. this.animationsEnabled = true;
  23811. this._animationPropertiesOverride = null;
  23812. /**
  23813. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23814. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23815. */
  23816. this.useConstantAnimationDeltaTime = false;
  23817. /**
  23818. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23819. * Please note that it requires to run a ray cast through the scene on every frame
  23820. */
  23821. this.constantlyUpdateMeshUnderPointer = false;
  23822. /**
  23823. * Defines the HTML cursor to use when hovering over interactive elements
  23824. */
  23825. this.hoverCursor = "pointer";
  23826. /**
  23827. * Defines the HTML default cursor to use (empty by default)
  23828. */
  23829. this.defaultCursor = "";
  23830. /**
  23831. * This is used to call preventDefault() on pointer down
  23832. * in order to block unwanted artifacts like system double clicks
  23833. */
  23834. this.preventDefaultOnPointerDown = true;
  23835. // Metadata
  23836. /**
  23837. * Gets or sets user defined metadata
  23838. */
  23839. this.metadata = null;
  23840. /**
  23841. * Use this array to add regular expressions used to disable offline support for specific urls
  23842. */
  23843. this.disableOfflineSupportExceptionRules = new Array();
  23844. /**
  23845. * An event triggered when the scene is disposed.
  23846. */
  23847. this.onDisposeObservable = new BABYLON.Observable();
  23848. this._onDisposeObserver = null;
  23849. /**
  23850. * An event triggered before rendering the scene (right after animations and physics)
  23851. */
  23852. this.onBeforeRenderObservable = new BABYLON.Observable();
  23853. this._onBeforeRenderObserver = null;
  23854. /**
  23855. * An event triggered after rendering the scene
  23856. */
  23857. this.onAfterRenderObservable = new BABYLON.Observable();
  23858. this._onAfterRenderObserver = null;
  23859. /**
  23860. * An event triggered before animating the scene
  23861. */
  23862. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23863. /**
  23864. * An event triggered after animations processing
  23865. */
  23866. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23867. /**
  23868. * An event triggered before draw calls are ready to be sent
  23869. */
  23870. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23871. /**
  23872. * An event triggered after draw calls have been sent
  23873. */
  23874. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23875. /**
  23876. * An event triggered when physic simulation is about to be run
  23877. */
  23878. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23879. /**
  23880. * An event triggered when physic simulation has been done
  23881. */
  23882. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23883. /**
  23884. * An event triggered when the scene is ready
  23885. */
  23886. this.onReadyObservable = new BABYLON.Observable();
  23887. /**
  23888. * An event triggered before rendering a camera
  23889. */
  23890. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23891. this._onBeforeCameraRenderObserver = null;
  23892. /**
  23893. * An event triggered after rendering a camera
  23894. */
  23895. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23896. this._onAfterCameraRenderObserver = null;
  23897. /**
  23898. * An event triggered when active meshes evaluation is about to start
  23899. */
  23900. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23901. /**
  23902. * An event triggered when active meshes evaluation is done
  23903. */
  23904. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23905. /**
  23906. * An event triggered when particles rendering is about to start
  23907. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23908. */
  23909. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23910. /**
  23911. * An event triggered when particles rendering is done
  23912. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23913. */
  23914. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23915. /**
  23916. * An event triggered when sprites rendering is about to start
  23917. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23918. */
  23919. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23920. /**
  23921. * An event triggered when sprites rendering is done
  23922. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23923. */
  23924. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23925. /**
  23926. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23927. */
  23928. this.onDataLoadedObservable = new BABYLON.Observable();
  23929. /**
  23930. * An event triggered when a camera is created
  23931. */
  23932. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23933. /**
  23934. * An event triggered when a camera is removed
  23935. */
  23936. this.onCameraRemovedObservable = new BABYLON.Observable();
  23937. /**
  23938. * An event triggered when a light is created
  23939. */
  23940. this.onNewLightAddedObservable = new BABYLON.Observable();
  23941. /**
  23942. * An event triggered when a light is removed
  23943. */
  23944. this.onLightRemovedObservable = new BABYLON.Observable();
  23945. /**
  23946. * An event triggered when a geometry is created
  23947. */
  23948. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23949. /**
  23950. * An event triggered when a geometry is removed
  23951. */
  23952. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23953. /**
  23954. * An event triggered when a transform node is created
  23955. */
  23956. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23957. /**
  23958. * An event triggered when a transform node is removed
  23959. */
  23960. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23961. /**
  23962. * An event triggered when a mesh is created
  23963. */
  23964. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23965. /**
  23966. * An event triggered when a mesh is removed
  23967. */
  23968. this.onMeshRemovedObservable = new BABYLON.Observable();
  23969. /**
  23970. * An event triggered when render targets are about to be rendered
  23971. * Can happen multiple times per frame.
  23972. */
  23973. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23974. /**
  23975. * An event triggered when render targets were rendered.
  23976. * Can happen multiple times per frame.
  23977. */
  23978. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23979. /**
  23980. * An event triggered before calculating deterministic simulation step
  23981. */
  23982. this.onBeforeStepObservable = new BABYLON.Observable();
  23983. /**
  23984. * An event triggered after calculating deterministic simulation step
  23985. */
  23986. this.onAfterStepObservable = new BABYLON.Observable();
  23987. /**
  23988. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23989. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23990. * 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)
  23991. */
  23992. this.onRenderingGroupObservable = new BABYLON.Observable();
  23993. // Animations
  23994. /**
  23995. * Gets a list of Animations associated with the scene
  23996. */
  23997. this.animations = [];
  23998. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23999. /**
  24000. * 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).
  24001. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24002. */
  24003. this.onPrePointerObservable = new BABYLON.Observable();
  24004. /**
  24005. * Observable event triggered each time an input event is received from the rendering canvas
  24006. */
  24007. this.onPointerObservable = new BABYLON.Observable();
  24008. this._meshPickProceed = false;
  24009. this._currentPickResult = null;
  24010. this._previousPickResult = null;
  24011. this._totalPointersPressed = 0;
  24012. this._doubleClickOccured = false;
  24013. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24014. this.cameraToUseForPointers = null;
  24015. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24016. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24017. this._startingPointerTime = 0;
  24018. this._previousStartingPointerTime = 0;
  24019. this._pointerCaptures = {};
  24020. // Deterministic lockstep
  24021. this._timeAccumulator = 0;
  24022. this._currentStepId = 0;
  24023. this._currentInternalStep = 0;
  24024. // Keyboard
  24025. /**
  24026. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24027. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24028. */
  24029. this.onPreKeyboardObservable = new BABYLON.Observable();
  24030. /**
  24031. * Observable event triggered each time an keyboard event is received from the hosting window
  24032. */
  24033. this.onKeyboardObservable = new BABYLON.Observable();
  24034. // Coordinates system
  24035. this._useRightHandedSystem = false;
  24036. // Fog
  24037. this._fogEnabled = true;
  24038. this._fogMode = Scene.FOGMODE_NONE;
  24039. /**
  24040. * Gets or sets the fog color to use
  24041. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24042. */
  24043. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24044. /**
  24045. * Gets or sets the fog density to use
  24046. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24047. */
  24048. this.fogDensity = 0.1;
  24049. /**
  24050. * Gets or sets the fog start distance to use
  24051. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24052. */
  24053. this.fogStart = 0;
  24054. /**
  24055. * Gets or sets the fog end distance to use
  24056. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24057. */
  24058. this.fogEnd = 1000.0;
  24059. // Lights
  24060. this._shadowsEnabled = true;
  24061. this._lightsEnabled = true;
  24062. /**
  24063. * All of the lights added to this scene
  24064. * @see http://doc.babylonjs.com/babylon101/lights
  24065. */
  24066. this.lights = new Array();
  24067. // Cameras
  24068. /** All of the cameras added to this scene.
  24069. * @see http://doc.babylonjs.com/babylon101/cameras
  24070. */
  24071. this.cameras = new Array();
  24072. /** All of the active cameras added to this scene. */
  24073. this.activeCameras = new Array();
  24074. // Meshes
  24075. /**
  24076. * All of the tranform nodes added to this scene
  24077. * @see http://doc.babylonjs.com/how_to/transformnode
  24078. */
  24079. this.transformNodes = new Array();
  24080. /**
  24081. * All of the (abstract) meshes added to this scene
  24082. */
  24083. this.meshes = new Array();
  24084. /**
  24085. * All of the animation groups added to this scene
  24086. * @see http://doc.babylonjs.com/how_to/group
  24087. */
  24088. this.animationGroups = new Array();
  24089. // Geometries
  24090. this._geometries = new Array();
  24091. /**
  24092. * All of the materials added to this scene
  24093. * @see http://doc.babylonjs.com/babylon101/materials
  24094. */
  24095. this.materials = new Array();
  24096. /**
  24097. * All of the multi-materials added to this scene
  24098. * @see http://doc.babylonjs.com/how_to/multi_materials
  24099. */
  24100. this.multiMaterials = new Array();
  24101. // Textures
  24102. this._texturesEnabled = true;
  24103. /**
  24104. * All of the textures added to this scene
  24105. */
  24106. this.textures = new Array();
  24107. // Particles
  24108. /**
  24109. * Gets or sets a boolean indicating if particles are enabled on this scene
  24110. */
  24111. this.particlesEnabled = true;
  24112. /**
  24113. * All of the particle systems added to this scene
  24114. * @see http://doc.babylonjs.com/babylon101/particles
  24115. */
  24116. this.particleSystems = new Array();
  24117. // Sprites
  24118. /**
  24119. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24120. */
  24121. this.spritesEnabled = true;
  24122. /**
  24123. * All of the sprite managers added to this scene
  24124. * @see http://doc.babylonjs.com/babylon101/sprites
  24125. */
  24126. this.spriteManagers = new Array();
  24127. /**
  24128. * The list of layers (background and foreground) of the scene
  24129. */
  24130. this.layers = new Array();
  24131. /**
  24132. * The list of effect layers (highlights/glow) added to the scene
  24133. * @see http://doc.babylonjs.com/how_to/highlight_layer
  24134. * @see http://doc.babylonjs.com/how_to/glow_layer
  24135. */
  24136. this.effectLayers = new Array();
  24137. // Skeletons
  24138. this._skeletonsEnabled = true;
  24139. /**
  24140. * The list of skeletons added to the scene
  24141. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24142. */
  24143. this.skeletons = new Array();
  24144. // Morph targets
  24145. /**
  24146. * The list of morph target managers added to the scene
  24147. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24148. */
  24149. this.morphTargetManagers = new Array();
  24150. // Lens flares
  24151. /**
  24152. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24153. */
  24154. this.lensFlaresEnabled = true;
  24155. /**
  24156. * The list of lens flare system added to the scene
  24157. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  24158. */
  24159. this.lensFlareSystems = new Array();
  24160. // Collisions
  24161. /**
  24162. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24163. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24164. */
  24165. this.collisionsEnabled = true;
  24166. /**
  24167. * Defines the gravity applied to this scene (used only for collisions)
  24168. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24169. */
  24170. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24171. // Postprocesses
  24172. /**
  24173. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24174. */
  24175. this.postProcessesEnabled = true;
  24176. /**
  24177. * The list of postprocesses added to the scene
  24178. */
  24179. this.postProcesses = new Array();
  24180. // Customs render targets
  24181. /**
  24182. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24183. */
  24184. this.renderTargetsEnabled = true;
  24185. /**
  24186. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24187. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24188. */
  24189. this.dumpNextRenderTargets = false;
  24190. /**
  24191. * The list of user defined render targets added to the scene
  24192. */
  24193. this.customRenderTargets = new Array();
  24194. /**
  24195. * Gets the list of meshes imported to the scene through SceneLoader
  24196. */
  24197. this.importedMeshesFiles = new Array();
  24198. // Probes
  24199. /**
  24200. * Gets or sets a boolean indicating if probes are enabled on this scene
  24201. */
  24202. this.probesEnabled = true;
  24203. /**
  24204. * The list of reflection probes added to the scene
  24205. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24206. */
  24207. this.reflectionProbes = new Array();
  24208. /** @hidden */
  24209. this._actionManagers = new Array();
  24210. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24211. // Procedural textures
  24212. /**
  24213. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24214. */
  24215. this.proceduralTexturesEnabled = true;
  24216. /**
  24217. * The list of procedural textures added to the scene
  24218. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24219. */
  24220. this.proceduralTextures = new Array();
  24221. /**
  24222. * The list of sound tracks added to the scene
  24223. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24224. */
  24225. this.soundTracks = new Array();
  24226. this._audioEnabled = true;
  24227. this._headphone = false;
  24228. // Performance counters
  24229. this._totalVertices = new BABYLON.PerfCounter();
  24230. /** @hidden */
  24231. this._activeIndices = new BABYLON.PerfCounter();
  24232. /** @hidden */
  24233. this._activeParticles = new BABYLON.PerfCounter();
  24234. /** @hidden */
  24235. this._activeBones = new BABYLON.PerfCounter();
  24236. this._animationTime = 0;
  24237. /**
  24238. * Gets or sets a general scale for animation speed
  24239. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24240. */
  24241. this.animationTimeScale = 1;
  24242. this._renderId = 0;
  24243. this._executeWhenReadyTimeoutId = -1;
  24244. this._intermediateRendering = false;
  24245. this._viewUpdateFlag = -1;
  24246. this._projectionUpdateFlag = -1;
  24247. this._alternateViewUpdateFlag = -1;
  24248. this._alternateProjectionUpdateFlag = -1;
  24249. /** @hidden */
  24250. this._toBeDisposed = new BABYLON.SmartArray(256);
  24251. this._activeRequests = new Array();
  24252. this._pendingData = new Array();
  24253. this._isDisposed = false;
  24254. /**
  24255. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24256. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24257. */
  24258. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24259. this._activeMeshes = new BABYLON.SmartArray(256);
  24260. this._processedMaterials = new BABYLON.SmartArray(256);
  24261. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24262. /** @hidden */
  24263. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24264. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24265. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24266. /** @hidden */
  24267. this._activeAnimatables = new Array();
  24268. this._transformMatrix = BABYLON.Matrix.Zero();
  24269. this._useAlternateCameraConfiguration = false;
  24270. this._alternateRendering = false;
  24271. /**
  24272. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24273. * This is useful if there are more lights that the maximum simulteanous authorized
  24274. */
  24275. this.requireLightSorting = false;
  24276. this._depthRenderer = {};
  24277. this._activeMeshesFrozen = false;
  24278. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24279. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24280. this._engine.scenes.push(this);
  24281. this._uid = null;
  24282. this._renderingManager = new BABYLON.RenderingManager(this);
  24283. if (BABYLON.PostProcessManager) {
  24284. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24285. }
  24286. if (BABYLON.OutlineRenderer) {
  24287. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24288. }
  24289. if (BABYLON.Tools.IsWindowObjectExist()) {
  24290. this.attachControl();
  24291. }
  24292. //simplification queue
  24293. if (BABYLON.SimplificationQueue) {
  24294. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24295. }
  24296. //collision coordinator initialization. For now legacy per default.
  24297. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24298. // Uniform Buffer
  24299. this._createUbo();
  24300. // Default Image processing definition
  24301. if (BABYLON.ImageProcessingConfiguration) {
  24302. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24303. }
  24304. }
  24305. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24306. /** The fog is deactivated */
  24307. get: function () {
  24308. return Scene._FOGMODE_NONE;
  24309. },
  24310. enumerable: true,
  24311. configurable: true
  24312. });
  24313. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24314. /** The fog density is following an exponential function */
  24315. get: function () {
  24316. return Scene._FOGMODE_EXP;
  24317. },
  24318. enumerable: true,
  24319. configurable: true
  24320. });
  24321. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24322. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24323. get: function () {
  24324. return Scene._FOGMODE_EXP2;
  24325. },
  24326. enumerable: true,
  24327. configurable: true
  24328. });
  24329. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24330. /** The fog density is following a linear function. */
  24331. get: function () {
  24332. return Scene._FOGMODE_LINEAR;
  24333. },
  24334. enumerable: true,
  24335. configurable: true
  24336. });
  24337. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24338. /**
  24339. * Texture used in all pbr material as the reflection texture.
  24340. * As in the majority of the scene they are the same (exception for multi room and so on),
  24341. * this is easier to reference from here than from all the materials.
  24342. */
  24343. get: function () {
  24344. return this._environmentTexture;
  24345. },
  24346. /**
  24347. * Texture used in all pbr material as the reflection texture.
  24348. * As in the majority of the scene they are the same (exception for multi room and so on),
  24349. * this is easier to set here than in all the materials.
  24350. */
  24351. set: function (value) {
  24352. if (this._environmentTexture === value) {
  24353. return;
  24354. }
  24355. this._environmentTexture = value;
  24356. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24357. },
  24358. enumerable: true,
  24359. configurable: true
  24360. });
  24361. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24362. /**
  24363. * Default image processing configuration used either in the rendering
  24364. * Forward main pass or through the imageProcessingPostProcess if present.
  24365. * As in the majority of the scene they are the same (exception for multi camera),
  24366. * this is easier to reference from here than from all the materials and post process.
  24367. *
  24368. * No setter as we it is a shared configuration, you can set the values instead.
  24369. */
  24370. get: function () {
  24371. return this._imageProcessingConfiguration;
  24372. },
  24373. enumerable: true,
  24374. configurable: true
  24375. });
  24376. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24377. get: function () {
  24378. return this._forceWireframe;
  24379. },
  24380. /**
  24381. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24382. */
  24383. set: function (value) {
  24384. if (this._forceWireframe === value) {
  24385. return;
  24386. }
  24387. this._forceWireframe = value;
  24388. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24389. },
  24390. enumerable: true,
  24391. configurable: true
  24392. });
  24393. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24394. get: function () {
  24395. return this._forcePointsCloud;
  24396. },
  24397. /**
  24398. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24399. */
  24400. set: function (value) {
  24401. if (this._forcePointsCloud === value) {
  24402. return;
  24403. }
  24404. this._forcePointsCloud = value;
  24405. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24406. },
  24407. enumerable: true,
  24408. configurable: true
  24409. });
  24410. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24411. /**
  24412. * Gets or sets the animation properties override
  24413. */
  24414. get: function () {
  24415. return this._animationPropertiesOverride;
  24416. },
  24417. set: function (value) {
  24418. this._animationPropertiesOverride = value;
  24419. },
  24420. enumerable: true,
  24421. configurable: true
  24422. });
  24423. Object.defineProperty(Scene.prototype, "onDispose", {
  24424. /** Sets a function to be executed when this scene is disposed. */
  24425. set: function (callback) {
  24426. if (this._onDisposeObserver) {
  24427. this.onDisposeObservable.remove(this._onDisposeObserver);
  24428. }
  24429. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24430. },
  24431. enumerable: true,
  24432. configurable: true
  24433. });
  24434. Object.defineProperty(Scene.prototype, "beforeRender", {
  24435. /** Sets a function to be executed before rendering this scene */
  24436. set: function (callback) {
  24437. if (this._onBeforeRenderObserver) {
  24438. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24439. }
  24440. if (callback) {
  24441. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24442. }
  24443. },
  24444. enumerable: true,
  24445. configurable: true
  24446. });
  24447. Object.defineProperty(Scene.prototype, "afterRender", {
  24448. /** Sets a function to be executed after rendering this scene */
  24449. set: function (callback) {
  24450. if (this._onAfterRenderObserver) {
  24451. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24452. }
  24453. if (callback) {
  24454. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24455. }
  24456. },
  24457. enumerable: true,
  24458. configurable: true
  24459. });
  24460. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24461. /** Sets a function to be executed before rendering a camera*/
  24462. set: function (callback) {
  24463. if (this._onBeforeCameraRenderObserver) {
  24464. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24465. }
  24466. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24467. },
  24468. enumerable: true,
  24469. configurable: true
  24470. });
  24471. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24472. /** Sets a function to be executed after rendering a camera*/
  24473. set: function (callback) {
  24474. if (this._onAfterCameraRenderObserver) {
  24475. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24476. }
  24477. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24478. },
  24479. enumerable: true,
  24480. configurable: true
  24481. });
  24482. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24483. /**
  24484. * Gets the gamepad manager associated with the scene
  24485. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24486. */
  24487. get: function () {
  24488. if (!this._gamepadManager) {
  24489. this._gamepadManager = new BABYLON.GamepadManager(this);
  24490. }
  24491. return this._gamepadManager;
  24492. },
  24493. enumerable: true,
  24494. configurable: true
  24495. });
  24496. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24497. /**
  24498. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24499. */
  24500. get: function () {
  24501. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24502. },
  24503. enumerable: true,
  24504. configurable: true
  24505. });
  24506. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24507. get: function () {
  24508. return this._useRightHandedSystem;
  24509. },
  24510. /**
  24511. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24512. */
  24513. set: function (value) {
  24514. if (this._useRightHandedSystem === value) {
  24515. return;
  24516. }
  24517. this._useRightHandedSystem = value;
  24518. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24519. },
  24520. enumerable: true,
  24521. configurable: true
  24522. });
  24523. /**
  24524. * Sets the step Id used by deterministic lock step
  24525. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24526. * @param newStepId defines the step Id
  24527. */
  24528. Scene.prototype.setStepId = function (newStepId) {
  24529. this._currentStepId = newStepId;
  24530. };
  24531. ;
  24532. /**
  24533. * Gets the step Id used by deterministic lock step
  24534. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24535. * @returns the step Id
  24536. */
  24537. Scene.prototype.getStepId = function () {
  24538. return this._currentStepId;
  24539. };
  24540. ;
  24541. /**
  24542. * Gets the internal step used by deterministic lock step
  24543. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24544. * @returns the internal step
  24545. */
  24546. Scene.prototype.getInternalStep = function () {
  24547. return this._currentInternalStep;
  24548. };
  24549. ;
  24550. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24551. get: function () {
  24552. return this._fogEnabled;
  24553. },
  24554. /**
  24555. * Gets or sets a boolean indicating if fog is enabled on this scene
  24556. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24557. */
  24558. set: function (value) {
  24559. if (this._fogEnabled === value) {
  24560. return;
  24561. }
  24562. this._fogEnabled = value;
  24563. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24564. },
  24565. enumerable: true,
  24566. configurable: true
  24567. });
  24568. Object.defineProperty(Scene.prototype, "fogMode", {
  24569. get: function () {
  24570. return this._fogMode;
  24571. },
  24572. /**
  24573. * Gets or sets the fog mode to use
  24574. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24575. */
  24576. set: function (value) {
  24577. if (this._fogMode === value) {
  24578. return;
  24579. }
  24580. this._fogMode = value;
  24581. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24582. },
  24583. enumerable: true,
  24584. configurable: true
  24585. });
  24586. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24587. get: function () {
  24588. return this._shadowsEnabled;
  24589. },
  24590. /**
  24591. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24592. */
  24593. set: function (value) {
  24594. if (this._shadowsEnabled === value) {
  24595. return;
  24596. }
  24597. this._shadowsEnabled = value;
  24598. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24599. },
  24600. enumerable: true,
  24601. configurable: true
  24602. });
  24603. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24604. get: function () {
  24605. return this._lightsEnabled;
  24606. },
  24607. /**
  24608. * Gets or sets a boolean indicating if lights are enabled on this scene
  24609. */
  24610. set: function (value) {
  24611. if (this._lightsEnabled === value) {
  24612. return;
  24613. }
  24614. this._lightsEnabled = value;
  24615. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24616. },
  24617. enumerable: true,
  24618. configurable: true
  24619. });
  24620. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24621. /** The default material used on meshes when no material is affected */
  24622. get: function () {
  24623. if (!this._defaultMaterial) {
  24624. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24625. }
  24626. return this._defaultMaterial;
  24627. },
  24628. /** The default material used on meshes when no material is affected */
  24629. set: function (value) {
  24630. this._defaultMaterial = value;
  24631. },
  24632. enumerable: true,
  24633. configurable: true
  24634. });
  24635. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24636. get: function () {
  24637. return this._texturesEnabled;
  24638. },
  24639. /**
  24640. * Gets or sets a boolean indicating if textures are enabled on this scene
  24641. */
  24642. set: function (value) {
  24643. if (this._texturesEnabled === value) {
  24644. return;
  24645. }
  24646. this._texturesEnabled = value;
  24647. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24648. },
  24649. enumerable: true,
  24650. configurable: true
  24651. });
  24652. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24653. get: function () {
  24654. return this._skeletonsEnabled;
  24655. },
  24656. /**
  24657. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24658. */
  24659. set: function (value) {
  24660. if (this._skeletonsEnabled === value) {
  24661. return;
  24662. }
  24663. this._skeletonsEnabled = value;
  24664. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24665. },
  24666. enumerable: true,
  24667. configurable: true
  24668. });
  24669. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24670. /**
  24671. * Gets the postprocess render pipeline manager
  24672. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24673. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24674. */
  24675. get: function () {
  24676. if (!this._postProcessRenderPipelineManager) {
  24677. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24678. }
  24679. return this._postProcessRenderPipelineManager;
  24680. },
  24681. enumerable: true,
  24682. configurable: true
  24683. });
  24684. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24685. /**
  24686. * Gets the main soundtrack associated with the scene
  24687. */
  24688. get: function () {
  24689. if (!this._mainSoundTrack) {
  24690. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24691. }
  24692. return this._mainSoundTrack;
  24693. },
  24694. enumerable: true,
  24695. configurable: true
  24696. });
  24697. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24698. /** @hidden */
  24699. get: function () {
  24700. return this._alternateRendering;
  24701. },
  24702. enumerable: true,
  24703. configurable: true
  24704. });
  24705. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24706. /**
  24707. * Gets the list of frustum planes (built from the active camera)
  24708. */
  24709. get: function () {
  24710. return this._frustumPlanes;
  24711. },
  24712. enumerable: true,
  24713. configurable: true
  24714. });
  24715. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24716. /**
  24717. * Gets the current geometry buffer associated to the scene.
  24718. */
  24719. get: function () {
  24720. return this._geometryBufferRenderer;
  24721. },
  24722. /**
  24723. * Sets the current geometry buffer for the scene.
  24724. */
  24725. set: function (geometryBufferRenderer) {
  24726. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24727. this._geometryBufferRenderer = geometryBufferRenderer;
  24728. }
  24729. },
  24730. enumerable: true,
  24731. configurable: true
  24732. });
  24733. Object.defineProperty(Scene.prototype, "debugLayer", {
  24734. /**
  24735. * Gets the debug layer (aka Inspector) associated with the scene
  24736. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24737. */
  24738. get: function () {
  24739. if (!this._debugLayer) {
  24740. this._debugLayer = new BABYLON.DebugLayer(this);
  24741. }
  24742. return this._debugLayer;
  24743. },
  24744. enumerable: true,
  24745. configurable: true
  24746. });
  24747. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24748. /**
  24749. * Gets a boolean indicating if collisions are processed on a web worker
  24750. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24751. */
  24752. get: function () {
  24753. return this._workerCollisions;
  24754. },
  24755. set: function (enabled) {
  24756. if (!BABYLON.CollisionCoordinatorLegacy) {
  24757. return;
  24758. }
  24759. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24760. this._workerCollisions = enabled;
  24761. if (this.collisionCoordinator) {
  24762. this.collisionCoordinator.destroy();
  24763. }
  24764. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24765. this.collisionCoordinator.init(this);
  24766. },
  24767. enumerable: true,
  24768. configurable: true
  24769. });
  24770. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24771. /**
  24772. * Gets the octree used to boost mesh selection (picking)
  24773. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24774. */
  24775. get: function () {
  24776. return this._selectionOctree;
  24777. },
  24778. enumerable: true,
  24779. configurable: true
  24780. });
  24781. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24782. /**
  24783. * Gets the mesh that is currently under the pointer
  24784. */
  24785. get: function () {
  24786. return this._pointerOverMesh;
  24787. },
  24788. enumerable: true,
  24789. configurable: true
  24790. });
  24791. Object.defineProperty(Scene.prototype, "pointerX", {
  24792. /**
  24793. * Gets the current on-screen X position of the pointer
  24794. */
  24795. get: function () {
  24796. return this._pointerX;
  24797. },
  24798. enumerable: true,
  24799. configurable: true
  24800. });
  24801. Object.defineProperty(Scene.prototype, "pointerY", {
  24802. /**
  24803. * Gets the current on-screen Y position of the pointer
  24804. */
  24805. get: function () {
  24806. return this._pointerY;
  24807. },
  24808. enumerable: true,
  24809. configurable: true
  24810. });
  24811. /**
  24812. * Gets the cached material (ie. the latest rendered one)
  24813. * @returns the cached material
  24814. */
  24815. Scene.prototype.getCachedMaterial = function () {
  24816. return this._cachedMaterial;
  24817. };
  24818. /**
  24819. * Gets the cached effect (ie. the latest rendered one)
  24820. * @returns the cached effect
  24821. */
  24822. Scene.prototype.getCachedEffect = function () {
  24823. return this._cachedEffect;
  24824. };
  24825. /**
  24826. * Gets the cached visibility state (ie. the latest rendered one)
  24827. * @returns the cached visibility state
  24828. */
  24829. Scene.prototype.getCachedVisibility = function () {
  24830. return this._cachedVisibility;
  24831. };
  24832. /**
  24833. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24834. * @param material defines the current material
  24835. * @param effect defines the current effect
  24836. * @param visibility defines the current visibility state
  24837. * @returns true if one parameter is not cached
  24838. */
  24839. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24840. if (visibility === void 0) { visibility = 1; }
  24841. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24842. };
  24843. /**
  24844. * Gets the bounding box renderer associated with the scene
  24845. * @returns a BoundingBoxRenderer
  24846. */
  24847. Scene.prototype.getBoundingBoxRenderer = function () {
  24848. if (!this._boundingBoxRenderer) {
  24849. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24850. }
  24851. return this._boundingBoxRenderer;
  24852. };
  24853. /**
  24854. * Gets the outline renderer associated with the scene
  24855. * @returns a OutlineRenderer
  24856. */
  24857. Scene.prototype.getOutlineRenderer = function () {
  24858. return this._outlineRenderer;
  24859. };
  24860. /**
  24861. * Gets the engine associated with the scene
  24862. * @returns an Engine
  24863. */
  24864. Scene.prototype.getEngine = function () {
  24865. return this._engine;
  24866. };
  24867. /**
  24868. * Gets the total number of vertices rendered per frame
  24869. * @returns the total number of vertices rendered per frame
  24870. */
  24871. Scene.prototype.getTotalVertices = function () {
  24872. return this._totalVertices.current;
  24873. };
  24874. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24875. /**
  24876. * Gets the performance counter for total vertices
  24877. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24878. */
  24879. get: function () {
  24880. return this._totalVertices;
  24881. },
  24882. enumerable: true,
  24883. configurable: true
  24884. });
  24885. /**
  24886. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24887. * @returns the total number of active indices rendered per frame
  24888. */
  24889. Scene.prototype.getActiveIndices = function () {
  24890. return this._activeIndices.current;
  24891. };
  24892. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24893. /**
  24894. * Gets the performance counter for active indices
  24895. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24896. */
  24897. get: function () {
  24898. return this._activeIndices;
  24899. },
  24900. enumerable: true,
  24901. configurable: true
  24902. });
  24903. /**
  24904. * Gets the total number of active particles rendered per frame
  24905. * @returns the total number of active particles rendered per frame
  24906. */
  24907. Scene.prototype.getActiveParticles = function () {
  24908. return this._activeParticles.current;
  24909. };
  24910. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24911. /**
  24912. * Gets the performance counter for active particles
  24913. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24914. */
  24915. get: function () {
  24916. return this._activeParticles;
  24917. },
  24918. enumerable: true,
  24919. configurable: true
  24920. });
  24921. /**
  24922. * Gets the total number of active bones rendered per frame
  24923. * @returns the total number of active bones rendered per frame
  24924. */
  24925. Scene.prototype.getActiveBones = function () {
  24926. return this._activeBones.current;
  24927. };
  24928. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24929. /**
  24930. * Gets the performance counter for active bones
  24931. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24932. */
  24933. get: function () {
  24934. return this._activeBones;
  24935. },
  24936. enumerable: true,
  24937. configurable: true
  24938. });
  24939. /** @hidden */
  24940. Scene.prototype.getInterFramePerfCounter = function () {
  24941. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24942. return 0;
  24943. };
  24944. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24945. /** @hidden */
  24946. get: function () {
  24947. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24948. return null;
  24949. },
  24950. enumerable: true,
  24951. configurable: true
  24952. });
  24953. /** @hidden */
  24954. Scene.prototype.getLastFrameDuration = function () {
  24955. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24956. return 0;
  24957. };
  24958. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24959. /** @hidden */
  24960. get: function () {
  24961. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24962. return null;
  24963. },
  24964. enumerable: true,
  24965. configurable: true
  24966. });
  24967. /** @hidden */
  24968. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24969. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24970. return 0;
  24971. };
  24972. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24973. /** @hidden */
  24974. get: function () {
  24975. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24976. return null;
  24977. },
  24978. enumerable: true,
  24979. configurable: true
  24980. });
  24981. /**
  24982. * Gets the array of active meshes
  24983. * @returns an array of AbstractMesh
  24984. */
  24985. Scene.prototype.getActiveMeshes = function () {
  24986. return this._activeMeshes;
  24987. };
  24988. /** @hidden */
  24989. Scene.prototype.getRenderTargetsDuration = function () {
  24990. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24991. return 0;
  24992. };
  24993. /** @hidden */
  24994. Scene.prototype.getRenderDuration = function () {
  24995. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24996. return 0;
  24997. };
  24998. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24999. /** @hidden */
  25000. get: function () {
  25001. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25002. return null;
  25003. },
  25004. enumerable: true,
  25005. configurable: true
  25006. });
  25007. /** @hidden */
  25008. Scene.prototype.getParticlesDuration = function () {
  25009. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25010. return 0;
  25011. };
  25012. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25013. /** @hidden */
  25014. get: function () {
  25015. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25016. return null;
  25017. },
  25018. enumerable: true,
  25019. configurable: true
  25020. });
  25021. /** @hidden */
  25022. Scene.prototype.getSpritesDuration = function () {
  25023. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25024. return 0;
  25025. };
  25026. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25027. /** @hidden */
  25028. get: function () {
  25029. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25030. return null;
  25031. },
  25032. enumerable: true,
  25033. configurable: true
  25034. });
  25035. /**
  25036. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25037. * @returns a number
  25038. */
  25039. Scene.prototype.getAnimationRatio = function () {
  25040. return this._animationRatio;
  25041. };
  25042. /**
  25043. * Gets an unique Id for the current frame
  25044. * @returns a number
  25045. */
  25046. Scene.prototype.getRenderId = function () {
  25047. return this._renderId;
  25048. };
  25049. /** Call this function if you want to manually increment the render Id*/
  25050. Scene.prototype.incrementRenderId = function () {
  25051. this._renderId++;
  25052. };
  25053. Scene.prototype._updatePointerPosition = function (evt) {
  25054. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25055. if (!canvasRect) {
  25056. return;
  25057. }
  25058. this._pointerX = evt.clientX - canvasRect.left;
  25059. this._pointerY = evt.clientY - canvasRect.top;
  25060. this._unTranslatedPointerX = this._pointerX;
  25061. this._unTranslatedPointerY = this._pointerY;
  25062. };
  25063. Scene.prototype._createUbo = function () {
  25064. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25065. this._sceneUbo.addUniform("viewProjection", 16);
  25066. this._sceneUbo.addUniform("view", 16);
  25067. };
  25068. Scene.prototype._createAlternateUbo = function () {
  25069. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25070. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25071. this._alternateSceneUbo.addUniform("view", 16);
  25072. };
  25073. // Pointers handling
  25074. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25075. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25076. if (result) {
  25077. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25078. }
  25079. return result;
  25080. };
  25081. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25082. if (pointerInfo.pickInfo) {
  25083. if (!pointerInfo.pickInfo.ray) {
  25084. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25085. }
  25086. }
  25087. };
  25088. /**
  25089. * Use this method to simulate a pointer move on a mesh
  25090. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25091. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25092. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25093. * @returns the current scene
  25094. */
  25095. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25096. var evt = new PointerEvent("pointermove", pointerEventInit);
  25097. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25098. return this;
  25099. }
  25100. return this._processPointerMove(pickResult, evt);
  25101. };
  25102. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25103. var canvas = this._engine.getRenderingCanvas();
  25104. if (!canvas) {
  25105. return this;
  25106. }
  25107. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25108. this.setPointerOverSprite(null);
  25109. this.setPointerOverMesh(pickResult.pickedMesh);
  25110. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25111. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25112. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25113. }
  25114. else {
  25115. canvas.style.cursor = this.hoverCursor;
  25116. }
  25117. }
  25118. else {
  25119. canvas.style.cursor = this.defaultCursor;
  25120. }
  25121. }
  25122. else {
  25123. this.setPointerOverMesh(null);
  25124. // Sprites
  25125. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25126. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25127. this.setPointerOverSprite(pickResult.pickedSprite);
  25128. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25129. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25130. }
  25131. else {
  25132. canvas.style.cursor = this.hoverCursor;
  25133. }
  25134. }
  25135. else {
  25136. this.setPointerOverSprite(null);
  25137. // Restore pointer
  25138. canvas.style.cursor = this.defaultCursor;
  25139. }
  25140. }
  25141. if (pickResult) {
  25142. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25143. if (this.onPointerMove) {
  25144. this.onPointerMove(evt, pickResult, type);
  25145. }
  25146. if (this.onPointerObservable.hasObservers()) {
  25147. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25148. this._setRayOnPointerInfo(pi);
  25149. this.onPointerObservable.notifyObservers(pi, type);
  25150. }
  25151. }
  25152. return this;
  25153. };
  25154. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25155. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25156. if (pickResult) {
  25157. pi.ray = pickResult.ray;
  25158. }
  25159. this.onPrePointerObservable.notifyObservers(pi, type);
  25160. if (pi.skipOnPointerObservable) {
  25161. return true;
  25162. }
  25163. else {
  25164. return false;
  25165. }
  25166. };
  25167. /**
  25168. * Use this method to simulate a pointer down on a mesh
  25169. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25170. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25171. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25172. * @returns the current scene
  25173. */
  25174. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25175. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25176. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25177. return this;
  25178. }
  25179. return this._processPointerDown(pickResult, evt);
  25180. };
  25181. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25182. var _this = this;
  25183. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25184. this._pickedDownMesh = pickResult.pickedMesh;
  25185. var actionManager = pickResult.pickedMesh.actionManager;
  25186. if (actionManager) {
  25187. if (actionManager.hasPickTriggers) {
  25188. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25189. switch (evt.button) {
  25190. case 0:
  25191. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25192. break;
  25193. case 1:
  25194. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25195. break;
  25196. case 2:
  25197. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25198. break;
  25199. }
  25200. }
  25201. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25202. window.setTimeout(function () {
  25203. 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);
  25204. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25205. if (_this._totalPointersPressed !== 0 &&
  25206. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25207. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25208. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25209. _this._startingPointerTime = 0;
  25210. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25211. }
  25212. }
  25213. }, Scene.LongPressDelay);
  25214. }
  25215. }
  25216. }
  25217. if (pickResult) {
  25218. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25219. if (this.onPointerDown) {
  25220. this.onPointerDown(evt, pickResult, type);
  25221. }
  25222. if (this.onPointerObservable.hasObservers()) {
  25223. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25224. this._setRayOnPointerInfo(pi);
  25225. this.onPointerObservable.notifyObservers(pi, type);
  25226. }
  25227. }
  25228. return this;
  25229. };
  25230. /**
  25231. * Use this method to simulate a pointer up on a mesh
  25232. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25233. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25234. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25235. * @returns the current scene
  25236. */
  25237. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25238. var evt = new PointerEvent("pointerup", pointerEventInit);
  25239. var clickInfo = new ClickInfo();
  25240. clickInfo.singleClick = true;
  25241. clickInfo.ignore = true;
  25242. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25243. return this;
  25244. }
  25245. return this._processPointerUp(pickResult, evt, clickInfo);
  25246. };
  25247. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25248. if (pickResult && pickResult && pickResult.pickedMesh) {
  25249. this._pickedUpMesh = pickResult.pickedMesh;
  25250. if (this._pickedDownMesh === this._pickedUpMesh) {
  25251. if (this.onPointerPick) {
  25252. this.onPointerPick(evt, pickResult);
  25253. }
  25254. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25255. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25256. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25257. this._setRayOnPointerInfo(pi);
  25258. this.onPointerObservable.notifyObservers(pi, type_1);
  25259. }
  25260. }
  25261. if (pickResult.pickedMesh.actionManager) {
  25262. if (clickInfo.ignore) {
  25263. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25264. }
  25265. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25266. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25267. }
  25268. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25269. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25270. }
  25271. }
  25272. }
  25273. if (this._pickedDownMesh &&
  25274. this._pickedDownMesh.actionManager &&
  25275. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25276. this._pickedDownMesh !== this._pickedUpMesh) {
  25277. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25278. }
  25279. var type = BABYLON.PointerEventTypes.POINTERUP;
  25280. if (this.onPointerObservable.hasObservers()) {
  25281. if (!clickInfo.ignore) {
  25282. if (!clickInfo.hasSwiped) {
  25283. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25284. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25285. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25286. this._setRayOnPointerInfo(pi);
  25287. this.onPointerObservable.notifyObservers(pi, type_2);
  25288. }
  25289. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25290. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25291. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25292. this._setRayOnPointerInfo(pi);
  25293. this.onPointerObservable.notifyObservers(pi, type_3);
  25294. }
  25295. }
  25296. }
  25297. else {
  25298. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25299. this._setRayOnPointerInfo(pi);
  25300. this.onPointerObservable.notifyObservers(pi, type);
  25301. }
  25302. }
  25303. if (this.onPointerUp) {
  25304. this.onPointerUp(evt, pickResult, type);
  25305. }
  25306. return this;
  25307. };
  25308. /**
  25309. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25310. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25311. * @returns true if the pointer was captured
  25312. */
  25313. Scene.prototype.isPointerCaptured = function (pointerId) {
  25314. if (pointerId === void 0) { pointerId = 0; }
  25315. return this._pointerCaptures[pointerId];
  25316. };
  25317. /**
  25318. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25319. * @param attachUp defines if you want to attach events to pointerup
  25320. * @param attachDown defines if you want to attach events to pointerdown
  25321. * @param attachMove defines if you want to attach events to pointermove
  25322. */
  25323. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25324. var _this = this;
  25325. if (attachUp === void 0) { attachUp = true; }
  25326. if (attachDown === void 0) { attachDown = true; }
  25327. if (attachMove === void 0) { attachMove = true; }
  25328. this._initActionManager = function (act, clickInfo) {
  25329. if (!_this._meshPickProceed) {
  25330. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25331. _this._currentPickResult = pickResult;
  25332. if (pickResult) {
  25333. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25334. }
  25335. _this._meshPickProceed = true;
  25336. }
  25337. return act;
  25338. };
  25339. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25340. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25341. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25342. btn !== _this._previousButtonPressed) {
  25343. _this._doubleClickOccured = false;
  25344. clickInfo.singleClick = true;
  25345. clickInfo.ignore = false;
  25346. cb(clickInfo, _this._currentPickResult);
  25347. }
  25348. };
  25349. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25350. var clickInfo = new ClickInfo();
  25351. _this._currentPickResult = null;
  25352. var act = null;
  25353. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25354. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25355. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25356. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25357. act = _this._initActionManager(act, clickInfo);
  25358. if (act)
  25359. checkPicking = act.hasPickTriggers;
  25360. }
  25361. if (checkPicking) {
  25362. var btn = evt.button;
  25363. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25364. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25365. if (!clickInfo.hasSwiped) {
  25366. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25367. if (!checkSingleClickImmediately) {
  25368. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25369. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25370. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25371. act = _this._initActionManager(act, clickInfo);
  25372. if (act)
  25373. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25374. }
  25375. }
  25376. if (checkSingleClickImmediately) {
  25377. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25378. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25379. btn !== _this._previousButtonPressed) {
  25380. clickInfo.singleClick = true;
  25381. cb(clickInfo, _this._currentPickResult);
  25382. }
  25383. }
  25384. // at least one double click is required to be check and exclusive double click is enabled
  25385. else {
  25386. // wait that no double click has been raised during the double click delay
  25387. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25388. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25389. }
  25390. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25391. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25392. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25393. act = _this._initActionManager(act, clickInfo);
  25394. if (act)
  25395. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25396. }
  25397. if (checkDoubleClick) {
  25398. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25399. if (btn === _this._previousButtonPressed &&
  25400. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25401. !_this._doubleClickOccured) {
  25402. // pointer has not moved for 2 clicks, it's a double click
  25403. if (!clickInfo.hasSwiped &&
  25404. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25405. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25406. _this._previousStartingPointerTime = 0;
  25407. _this._doubleClickOccured = true;
  25408. clickInfo.doubleClick = true;
  25409. clickInfo.ignore = false;
  25410. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25411. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25412. }
  25413. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25414. cb(clickInfo, _this._currentPickResult);
  25415. }
  25416. // if the two successive clicks are too far, it's just two simple clicks
  25417. else {
  25418. _this._doubleClickOccured = false;
  25419. _this._previousStartingPointerTime = _this._startingPointerTime;
  25420. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25421. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25422. _this._previousButtonPressed = btn;
  25423. if (Scene.ExclusiveDoubleClickMode) {
  25424. if (_this._previousDelayedSimpleClickTimeout) {
  25425. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25426. }
  25427. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25428. cb(clickInfo, _this._previousPickResult);
  25429. }
  25430. else {
  25431. cb(clickInfo, _this._currentPickResult);
  25432. }
  25433. }
  25434. }
  25435. // just the first click of the double has been raised
  25436. else {
  25437. _this._doubleClickOccured = false;
  25438. _this._previousStartingPointerTime = _this._startingPointerTime;
  25439. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25440. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25441. _this._previousButtonPressed = btn;
  25442. }
  25443. }
  25444. }
  25445. }
  25446. clickInfo.ignore = true;
  25447. cb(clickInfo, _this._currentPickResult);
  25448. };
  25449. this._spritePredicate = function (sprite) {
  25450. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25451. };
  25452. this._onPointerMove = function (evt) {
  25453. _this._updatePointerPosition(evt);
  25454. // PreObservable support
  25455. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25456. return;
  25457. }
  25458. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25459. return;
  25460. }
  25461. if (!_this.pointerMovePredicate) {
  25462. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25463. }
  25464. // Meshes
  25465. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25466. _this._processPointerMove(pickResult, evt);
  25467. };
  25468. this._onPointerDown = function (evt) {
  25469. _this._totalPointersPressed++;
  25470. _this._pickedDownMesh = null;
  25471. _this._meshPickProceed = false;
  25472. _this._updatePointerPosition(evt);
  25473. if (_this.preventDefaultOnPointerDown && canvas) {
  25474. evt.preventDefault();
  25475. canvas.focus();
  25476. }
  25477. // PreObservable support
  25478. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25479. return;
  25480. }
  25481. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25482. return;
  25483. }
  25484. _this._pointerCaptures[evt.pointerId] = true;
  25485. _this._startingPointerPosition.x = _this._pointerX;
  25486. _this._startingPointerPosition.y = _this._pointerY;
  25487. _this._startingPointerTime = Date.now();
  25488. if (!_this.pointerDownPredicate) {
  25489. _this.pointerDownPredicate = function (mesh) {
  25490. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25491. };
  25492. }
  25493. // Meshes
  25494. _this._pickedDownMesh = null;
  25495. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25496. _this._processPointerDown(pickResult, evt);
  25497. // Sprites
  25498. _this._pickedDownSprite = null;
  25499. if (_this.spriteManagers.length > 0) {
  25500. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25501. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25502. if (pickResult.pickedSprite.actionManager) {
  25503. _this._pickedDownSprite = pickResult.pickedSprite;
  25504. switch (evt.button) {
  25505. case 0:
  25506. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25507. break;
  25508. case 1:
  25509. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25510. break;
  25511. case 2:
  25512. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25513. break;
  25514. }
  25515. if (pickResult.pickedSprite.actionManager) {
  25516. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25517. }
  25518. }
  25519. }
  25520. }
  25521. };
  25522. this._onPointerUp = function (evt) {
  25523. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25524. return; // So we need to test it the pointer down was pressed before.
  25525. }
  25526. _this._totalPointersPressed--;
  25527. _this._pickedUpMesh = null;
  25528. _this._meshPickProceed = false;
  25529. _this._updatePointerPosition(evt);
  25530. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25531. // PreObservable support
  25532. if (_this.onPrePointerObservable.hasObservers()) {
  25533. if (!clickInfo.ignore) {
  25534. if (!clickInfo.hasSwiped) {
  25535. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25536. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25537. return;
  25538. }
  25539. }
  25540. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25541. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25542. return;
  25543. }
  25544. }
  25545. }
  25546. }
  25547. else {
  25548. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25549. return;
  25550. }
  25551. }
  25552. }
  25553. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25554. return;
  25555. }
  25556. _this._pointerCaptures[evt.pointerId] = false;
  25557. if (!_this.pointerUpPredicate) {
  25558. _this.pointerUpPredicate = function (mesh) {
  25559. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25560. };
  25561. }
  25562. // Meshes
  25563. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25564. _this._initActionManager(null, clickInfo);
  25565. }
  25566. if (!pickResult) {
  25567. pickResult = _this._currentPickResult;
  25568. }
  25569. _this._processPointerUp(pickResult, evt, clickInfo);
  25570. // Sprites
  25571. if (!clickInfo.ignore) {
  25572. if (_this.spriteManagers.length > 0) {
  25573. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25574. if (spritePickResult) {
  25575. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25576. if (spritePickResult.pickedSprite.actionManager) {
  25577. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25578. if (spritePickResult.pickedSprite.actionManager) {
  25579. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25580. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25581. }
  25582. }
  25583. }
  25584. }
  25585. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25586. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25587. }
  25588. }
  25589. }
  25590. }
  25591. _this._previousPickResult = _this._currentPickResult;
  25592. });
  25593. };
  25594. this._onKeyDown = function (evt) {
  25595. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25596. if (_this.onPreKeyboardObservable.hasObservers()) {
  25597. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25598. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25599. if (pi.skipOnPointerObservable) {
  25600. return;
  25601. }
  25602. }
  25603. if (_this.onKeyboardObservable.hasObservers()) {
  25604. var pi = new BABYLON.KeyboardInfo(type, evt);
  25605. _this.onKeyboardObservable.notifyObservers(pi, type);
  25606. }
  25607. if (_this.actionManager) {
  25608. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25609. }
  25610. };
  25611. this._onKeyUp = function (evt) {
  25612. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25613. if (_this.onPreKeyboardObservable.hasObservers()) {
  25614. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25615. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25616. if (pi.skipOnPointerObservable) {
  25617. return;
  25618. }
  25619. }
  25620. if (_this.onKeyboardObservable.hasObservers()) {
  25621. var pi = new BABYLON.KeyboardInfo(type, evt);
  25622. _this.onKeyboardObservable.notifyObservers(pi, type);
  25623. }
  25624. if (_this.actionManager) {
  25625. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25626. }
  25627. };
  25628. var engine = this.getEngine();
  25629. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25630. if (!canvas) {
  25631. return;
  25632. }
  25633. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25634. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25635. });
  25636. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25637. if (!canvas) {
  25638. return;
  25639. }
  25640. canvas.removeEventListener("keydown", _this._onKeyDown);
  25641. canvas.removeEventListener("keyup", _this._onKeyUp);
  25642. });
  25643. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25644. var canvas = this._engine.getRenderingCanvas();
  25645. if (!canvas) {
  25646. return;
  25647. }
  25648. if (attachMove) {
  25649. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25650. // Wheel
  25651. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25652. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25653. }
  25654. if (attachDown) {
  25655. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25656. }
  25657. if (attachUp) {
  25658. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25659. }
  25660. canvas.tabIndex = 1;
  25661. };
  25662. /** Detaches all event handlers*/
  25663. Scene.prototype.detachControl = function () {
  25664. var engine = this.getEngine();
  25665. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25666. var canvas = engine.getRenderingCanvas();
  25667. if (!canvas) {
  25668. return;
  25669. }
  25670. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25671. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25672. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25673. if (this._onCanvasBlurObserver) {
  25674. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25675. }
  25676. if (this._onCanvasFocusObserver) {
  25677. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25678. }
  25679. // Wheel
  25680. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25681. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25682. // Keyboard
  25683. canvas.removeEventListener("keydown", this._onKeyDown);
  25684. canvas.removeEventListener("keyup", this._onKeyUp);
  25685. // Observables
  25686. this.onKeyboardObservable.clear();
  25687. this.onPreKeyboardObservable.clear();
  25688. this.onPointerObservable.clear();
  25689. this.onPrePointerObservable.clear();
  25690. };
  25691. /**
  25692. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25693. * Delay loaded resources are not taking in account
  25694. * @return true if all required resources are ready
  25695. */
  25696. Scene.prototype.isReady = function () {
  25697. if (this._isDisposed) {
  25698. return false;
  25699. }
  25700. if (this._pendingData.length > 0) {
  25701. return false;
  25702. }
  25703. var index;
  25704. var engine = this.getEngine();
  25705. // Geometries
  25706. for (index = 0; index < this._geometries.length; index++) {
  25707. var geometry = this._geometries[index];
  25708. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25709. return false;
  25710. }
  25711. }
  25712. // Meshes
  25713. for (index = 0; index < this.meshes.length; index++) {
  25714. var mesh = this.meshes[index];
  25715. if (!mesh.isEnabled()) {
  25716. continue;
  25717. }
  25718. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25719. continue;
  25720. }
  25721. if (!mesh.isReady(true)) {
  25722. return false;
  25723. }
  25724. // Effect layers
  25725. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25726. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25727. var layer = _a[_i];
  25728. if (!layer.hasMesh(mesh)) {
  25729. continue;
  25730. }
  25731. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25732. var subMesh = _c[_b];
  25733. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25734. return false;
  25735. }
  25736. }
  25737. }
  25738. }
  25739. // Post-processes
  25740. if (this.activeCameras && this.activeCameras.length > 0) {
  25741. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25742. var camera = _e[_d];
  25743. if (!camera.isReady(true)) {
  25744. return false;
  25745. }
  25746. }
  25747. }
  25748. else if (this.activeCamera) {
  25749. if (!this.activeCamera.isReady(true)) {
  25750. return false;
  25751. }
  25752. }
  25753. // Particles
  25754. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25755. var particleSystem = _g[_f];
  25756. if (!particleSystem.isReady()) {
  25757. return false;
  25758. }
  25759. }
  25760. return true;
  25761. };
  25762. /** Resets all cached information relative to material (including effect and visibility) */
  25763. Scene.prototype.resetCachedMaterial = function () {
  25764. this._cachedMaterial = null;
  25765. this._cachedEffect = null;
  25766. this._cachedVisibility = null;
  25767. };
  25768. /**
  25769. * Registers a function to be called before every frame render
  25770. * @param func defines the function to register
  25771. */
  25772. Scene.prototype.registerBeforeRender = function (func) {
  25773. this.onBeforeRenderObservable.add(func);
  25774. };
  25775. /**
  25776. * Unregisters a function called before every frame render
  25777. * @param func defines the function to unregister
  25778. */
  25779. Scene.prototype.unregisterBeforeRender = function (func) {
  25780. this.onBeforeRenderObservable.removeCallback(func);
  25781. };
  25782. /**
  25783. * Registers a function to be called after every frame render
  25784. * @param func defines the function to register
  25785. */
  25786. Scene.prototype.registerAfterRender = function (func) {
  25787. this.onAfterRenderObservable.add(func);
  25788. };
  25789. /**
  25790. * Unregisters a function called after every frame render
  25791. * @param func defines the function to unregister
  25792. */
  25793. Scene.prototype.unregisterAfterRender = function (func) {
  25794. this.onAfterRenderObservable.removeCallback(func);
  25795. };
  25796. Scene.prototype._executeOnceBeforeRender = function (func) {
  25797. var _this = this;
  25798. var execFunc = function () {
  25799. func();
  25800. setTimeout(function () {
  25801. _this.unregisterBeforeRender(execFunc);
  25802. });
  25803. };
  25804. this.registerBeforeRender(execFunc);
  25805. };
  25806. /**
  25807. * The provided function will run before render once and will be disposed afterwards.
  25808. * A timeout delay can be provided so that the function will be executed in N ms.
  25809. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25810. * @param func The function to be executed.
  25811. * @param timeout optional delay in ms
  25812. */
  25813. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25814. var _this = this;
  25815. if (timeout !== undefined) {
  25816. setTimeout(function () {
  25817. _this._executeOnceBeforeRender(func);
  25818. }, timeout);
  25819. }
  25820. else {
  25821. this._executeOnceBeforeRender(func);
  25822. }
  25823. };
  25824. /** @hidden */
  25825. Scene.prototype._addPendingData = function (data) {
  25826. this._pendingData.push(data);
  25827. };
  25828. /** @hidden */
  25829. Scene.prototype._removePendingData = function (data) {
  25830. var wasLoading = this.isLoading;
  25831. var index = this._pendingData.indexOf(data);
  25832. if (index !== -1) {
  25833. this._pendingData.splice(index, 1);
  25834. }
  25835. if (wasLoading && !this.isLoading) {
  25836. this.onDataLoadedObservable.notifyObservers(this);
  25837. }
  25838. };
  25839. /**
  25840. * Returns the number of items waiting to be loaded
  25841. * @returns the number of items waiting to be loaded
  25842. */
  25843. Scene.prototype.getWaitingItemsCount = function () {
  25844. return this._pendingData.length;
  25845. };
  25846. Object.defineProperty(Scene.prototype, "isLoading", {
  25847. /**
  25848. * Returns a boolean indicating if the scene is still loading data
  25849. */
  25850. get: function () {
  25851. return this._pendingData.length > 0;
  25852. },
  25853. enumerable: true,
  25854. configurable: true
  25855. });
  25856. /**
  25857. * Registers a function to be executed when the scene is ready
  25858. * @param {Function} func - the function to be executed
  25859. */
  25860. Scene.prototype.executeWhenReady = function (func) {
  25861. var _this = this;
  25862. this.onReadyObservable.add(func);
  25863. if (this._executeWhenReadyTimeoutId !== -1) {
  25864. return;
  25865. }
  25866. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25867. _this._checkIsReady();
  25868. }, 150);
  25869. };
  25870. /**
  25871. * Returns a promise that resolves when the scene is ready
  25872. * @returns A promise that resolves when the scene is ready
  25873. */
  25874. Scene.prototype.whenReadyAsync = function () {
  25875. var _this = this;
  25876. return new Promise(function (resolve) {
  25877. _this.executeWhenReady(function () {
  25878. resolve();
  25879. });
  25880. });
  25881. };
  25882. /** @hidden */
  25883. Scene.prototype._checkIsReady = function () {
  25884. var _this = this;
  25885. if (this.isReady()) {
  25886. this.onReadyObservable.notifyObservers(this);
  25887. this.onReadyObservable.clear();
  25888. this._executeWhenReadyTimeoutId = -1;
  25889. return;
  25890. }
  25891. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25892. _this._checkIsReady();
  25893. }, 150);
  25894. };
  25895. // Animations
  25896. /**
  25897. * Will start the animation sequence of a given target
  25898. * @param target defines the target
  25899. * @param from defines from which frame should animation start
  25900. * @param to defines until which frame should animation run.
  25901. * @param weight defines the weight to apply to the animation (1.0 by default)
  25902. * @param loop defines if the animation loops
  25903. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25904. * @param onAnimationEnd defines the function to be executed when the animation ends
  25905. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25906. * @returns the animatable object created for this animation
  25907. */
  25908. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25909. if (weight === void 0) { weight = 1.0; }
  25910. if (speedRatio === void 0) { speedRatio = 1.0; }
  25911. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25912. returnedAnimatable.weight = weight;
  25913. return returnedAnimatable;
  25914. };
  25915. /**
  25916. * Will start the animation sequence of a given target
  25917. * @param target defines the target
  25918. * @param from defines from which frame should animation start
  25919. * @param to defines until which frame should animation run.
  25920. * @param loop defines if the animation loops
  25921. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25922. * @param onAnimationEnd defines the function to be executed when the animation ends
  25923. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25924. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25925. * @returns the animatable object created for this animation
  25926. */
  25927. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25928. if (speedRatio === void 0) { speedRatio = 1.0; }
  25929. if (stopCurrent === void 0) { stopCurrent = true; }
  25930. if (from > to && speedRatio > 0) {
  25931. speedRatio *= -1;
  25932. }
  25933. if (stopCurrent) {
  25934. this.stopAnimation(target);
  25935. }
  25936. if (!animatable) {
  25937. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25938. }
  25939. // Local animations
  25940. if (target.animations) {
  25941. animatable.appendAnimations(target, target.animations);
  25942. }
  25943. // Children animations
  25944. if (target.getAnimatables) {
  25945. var animatables = target.getAnimatables();
  25946. for (var index = 0; index < animatables.length; index++) {
  25947. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25948. }
  25949. }
  25950. animatable.reset();
  25951. return animatable;
  25952. };
  25953. /**
  25954. * Begin a new animation on a given node
  25955. * @param target defines the target where the animation will take place
  25956. * @param animations defines the list of animations to start
  25957. * @param from defines the initial value
  25958. * @param to defines the final value
  25959. * @param loop defines if you want animation to loop (off by default)
  25960. * @param speedRatio defines the speed ratio to apply to all animations
  25961. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25962. * @returns the list of created animatables
  25963. */
  25964. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25965. if (speedRatio === undefined) {
  25966. speedRatio = 1.0;
  25967. }
  25968. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25969. return animatable;
  25970. };
  25971. /**
  25972. * Begin a new animation on a given node and its hierarchy
  25973. * @param target defines the root node where the animation will take place
  25974. * @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.
  25975. * @param animations defines the list of animations to start
  25976. * @param from defines the initial value
  25977. * @param to defines the final value
  25978. * @param loop defines if you want animation to loop (off by default)
  25979. * @param speedRatio defines the speed ratio to apply to all animations
  25980. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25981. * @returns the list of animatables created for all nodes
  25982. */
  25983. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25984. var children = target.getDescendants(directDescendantsOnly);
  25985. var result = [];
  25986. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25987. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25988. var child = children_1[_i];
  25989. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25990. }
  25991. return result;
  25992. };
  25993. /**
  25994. * Gets the animatable associated with a specific target
  25995. * @param target defines the target of the animatable
  25996. * @returns the required animatable if found
  25997. */
  25998. Scene.prototype.getAnimatableByTarget = function (target) {
  25999. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26000. if (this._activeAnimatables[index].target === target) {
  26001. return this._activeAnimatables[index];
  26002. }
  26003. }
  26004. return null;
  26005. };
  26006. /**
  26007. * Gets all animatables associated with a given target
  26008. * @param target defines the target to look animatables for
  26009. * @returns an array of Animatables
  26010. */
  26011. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26012. var result = [];
  26013. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26014. if (this._activeAnimatables[index].target === target) {
  26015. result.push(this._activeAnimatables[index]);
  26016. }
  26017. }
  26018. return result;
  26019. };
  26020. Object.defineProperty(Scene.prototype, "animatables", {
  26021. /**
  26022. * Gets all animatable attached to the scene
  26023. */
  26024. get: function () {
  26025. return this._activeAnimatables;
  26026. },
  26027. enumerable: true,
  26028. configurable: true
  26029. });
  26030. /**
  26031. * Will stop the animation of the given target
  26032. * @param target - the target
  26033. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  26034. */
  26035. Scene.prototype.stopAnimation = function (target, animationName) {
  26036. var animatables = this.getAllAnimatablesByTarget(target);
  26037. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26038. var animatable = animatables_1[_i];
  26039. animatable.stop(animationName);
  26040. }
  26041. };
  26042. /**
  26043. * Stops and removes all animations that have been applied to the scene
  26044. */
  26045. Scene.prototype.stopAllAnimations = function () {
  26046. if (this._activeAnimatables) {
  26047. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26048. this._activeAnimatables[i].stop();
  26049. }
  26050. this._activeAnimatables = [];
  26051. }
  26052. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26053. var group = _a[_i];
  26054. group.stop();
  26055. }
  26056. };
  26057. Scene.prototype._animate = function () {
  26058. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26059. return;
  26060. }
  26061. // Getting time
  26062. var now = BABYLON.Tools.Now;
  26063. if (!this._animationTimeLast) {
  26064. if (this._pendingData.length > 0) {
  26065. return;
  26066. }
  26067. this._animationTimeLast = now;
  26068. }
  26069. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26070. this._animationTime += deltaTime;
  26071. this._animationTimeLast = now;
  26072. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26073. this._activeAnimatables[index]._animate(this._animationTime);
  26074. }
  26075. // Late animation bindings
  26076. this._processLateAnimationBindings();
  26077. };
  26078. /** @hidden */
  26079. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26080. var target = runtimeAnimation.target;
  26081. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26082. if (!target._lateAnimationHolders) {
  26083. target._lateAnimationHolders = {};
  26084. }
  26085. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26086. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26087. totalWeight: 0,
  26088. animations: [],
  26089. originalValue: originalValue
  26090. };
  26091. }
  26092. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26093. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26094. };
  26095. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26096. var normalizer = 1.0;
  26097. var finalPosition = BABYLON.Tmp.Vector3[0];
  26098. var finalScaling = BABYLON.Tmp.Vector3[1];
  26099. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26100. var startIndex = 0;
  26101. var originalAnimation = holder.animations[0];
  26102. var originalValue = holder.originalValue;
  26103. var scale = 1;
  26104. if (holder.totalWeight < 1.0) {
  26105. // We need to mix the original value in
  26106. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26107. scale = 1.0 - holder.totalWeight;
  26108. }
  26109. else {
  26110. startIndex = 1;
  26111. // We need to normalize the weights
  26112. normalizer = holder.totalWeight;
  26113. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26114. scale = originalAnimation.weight / normalizer;
  26115. if (scale == 1) {
  26116. return originalAnimation.currentValue;
  26117. }
  26118. }
  26119. finalScaling.scaleInPlace(scale);
  26120. finalPosition.scaleInPlace(scale);
  26121. finalQuaternion.scaleInPlace(scale);
  26122. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26123. var runtimeAnimation = holder.animations[animIndex];
  26124. var scale = runtimeAnimation.weight / normalizer;
  26125. var currentPosition = BABYLON.Tmp.Vector3[2];
  26126. var currentScaling = BABYLON.Tmp.Vector3[3];
  26127. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26128. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26129. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26130. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26131. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26132. }
  26133. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26134. return originalAnimation._workValue;
  26135. };
  26136. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26137. var originalAnimation = holder.animations[0];
  26138. var originalValue = holder.originalValue;
  26139. if (holder.animations.length === 1) {
  26140. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26141. }
  26142. var normalizer = 1.0;
  26143. var quaternions;
  26144. var weights;
  26145. if (holder.totalWeight < 1.0) {
  26146. var scale = 1.0 - holder.totalWeight;
  26147. quaternions = [];
  26148. weights = [];
  26149. quaternions.push(originalValue);
  26150. weights.push(scale);
  26151. }
  26152. else {
  26153. if (holder.animations.length === 2) { // Slerp as soon as we can
  26154. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26155. }
  26156. quaternions = [];
  26157. weights = [];
  26158. normalizer = holder.totalWeight;
  26159. }
  26160. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26161. var runtimeAnimation = holder.animations[animIndex];
  26162. quaternions.push(runtimeAnimation.currentValue);
  26163. weights.push(runtimeAnimation.weight / normalizer);
  26164. }
  26165. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26166. var cumulativeAmount = 0;
  26167. var cumulativeQuaternion = null;
  26168. for (var index = 0; index < quaternions.length;) {
  26169. if (!cumulativeQuaternion) {
  26170. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26171. cumulativeAmount = weights[index] + weights[index + 1];
  26172. index += 2;
  26173. continue;
  26174. }
  26175. cumulativeAmount += weights[index];
  26176. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26177. index++;
  26178. }
  26179. return cumulativeQuaternion;
  26180. };
  26181. Scene.prototype._processLateAnimationBindings = function () {
  26182. if (!this._registeredForLateAnimationBindings.length) {
  26183. return;
  26184. }
  26185. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26186. var target = this._registeredForLateAnimationBindings.data[index];
  26187. for (var path in target._lateAnimationHolders) {
  26188. var holder = target._lateAnimationHolders[path];
  26189. var originalAnimation = holder.animations[0];
  26190. var originalValue = holder.originalValue;
  26191. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26192. var finalValue = void 0;
  26193. if (matrixDecomposeMode) {
  26194. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26195. }
  26196. else {
  26197. var quaternionMode = originalValue.w !== undefined;
  26198. if (quaternionMode) {
  26199. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26200. }
  26201. else {
  26202. var startIndex = 0;
  26203. var normalizer = 1.0;
  26204. if (holder.totalWeight < 1.0) {
  26205. // We need to mix the original value in
  26206. if (originalValue.scale) {
  26207. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26208. }
  26209. else {
  26210. finalValue = originalValue * (1.0 - holder.totalWeight);
  26211. }
  26212. }
  26213. else {
  26214. // We need to normalize the weights
  26215. normalizer = holder.totalWeight;
  26216. var scale_1 = originalAnimation.weight / normalizer;
  26217. if (scale_1 !== 1) {
  26218. if (originalAnimation.currentValue.scale) {
  26219. finalValue = originalAnimation.currentValue.scale(scale_1);
  26220. }
  26221. else {
  26222. finalValue = originalAnimation.currentValue * scale_1;
  26223. }
  26224. }
  26225. else {
  26226. finalValue = originalAnimation.currentValue;
  26227. }
  26228. startIndex = 1;
  26229. }
  26230. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26231. var runtimeAnimation = holder.animations[animIndex];
  26232. var scale = runtimeAnimation.weight / normalizer;
  26233. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26234. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26235. }
  26236. else {
  26237. finalValue += runtimeAnimation.currentValue * scale;
  26238. }
  26239. }
  26240. }
  26241. }
  26242. target[path] = finalValue;
  26243. }
  26244. target._lateAnimationHolders = {};
  26245. }
  26246. this._registeredForLateAnimationBindings.reset();
  26247. };
  26248. // Matrix
  26249. /** @hidden */
  26250. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26251. this._useAlternateCameraConfiguration = active;
  26252. };
  26253. /**
  26254. * Gets the current view matrix
  26255. * @returns a Matrix
  26256. */
  26257. Scene.prototype.getViewMatrix = function () {
  26258. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26259. };
  26260. /**
  26261. * Gets the current projection matrix
  26262. * @returns a Matrix
  26263. */
  26264. Scene.prototype.getProjectionMatrix = function () {
  26265. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26266. };
  26267. /**
  26268. * Gets the current transform matrix
  26269. * @returns a Matrix made of View * Projection
  26270. */
  26271. Scene.prototype.getTransformMatrix = function () {
  26272. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26273. };
  26274. /**
  26275. * Sets the current transform matrix
  26276. * @param view defines the View matrix to use
  26277. * @param projection defines the Projection matrix to use
  26278. */
  26279. Scene.prototype.setTransformMatrix = function (view, projection) {
  26280. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26281. return;
  26282. }
  26283. this._viewUpdateFlag = view.updateFlag;
  26284. this._projectionUpdateFlag = projection.updateFlag;
  26285. this._viewMatrix = view;
  26286. this._projectionMatrix = projection;
  26287. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26288. // Update frustum
  26289. if (!this._frustumPlanes) {
  26290. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26291. }
  26292. else {
  26293. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26294. }
  26295. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26296. var otherCamera = this.activeCamera._alternateCamera;
  26297. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26298. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26299. }
  26300. if (this._sceneUbo.useUbo) {
  26301. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26302. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26303. this._sceneUbo.update();
  26304. }
  26305. };
  26306. /** @hidden */
  26307. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26308. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26309. return;
  26310. }
  26311. this._alternateViewUpdateFlag = view.updateFlag;
  26312. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26313. this._alternateViewMatrix = view;
  26314. this._alternateProjectionMatrix = projection;
  26315. if (!this._alternateTransformMatrix) {
  26316. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26317. }
  26318. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26319. if (!this._alternateSceneUbo) {
  26320. this._createAlternateUbo();
  26321. }
  26322. if (this._alternateSceneUbo.useUbo) {
  26323. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26324. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26325. this._alternateSceneUbo.update();
  26326. }
  26327. };
  26328. /**
  26329. * Gets the uniform buffer used to store scene data
  26330. * @returns a UniformBuffer
  26331. */
  26332. Scene.prototype.getSceneUniformBuffer = function () {
  26333. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26334. };
  26335. /**
  26336. * Gets an unique (relatively to the current scene) Id
  26337. * @returns an unique number for the scene
  26338. */
  26339. Scene.prototype.getUniqueId = function () {
  26340. var result = Scene._uniqueIdCounter;
  26341. Scene._uniqueIdCounter++;
  26342. return result;
  26343. };
  26344. /**
  26345. * Add a mesh to the list of scene's meshes
  26346. * @param newMesh defines the mesh to add
  26347. * @param recursive if all child meshes should also be added to the scene
  26348. */
  26349. Scene.prototype.addMesh = function (newMesh, recursive) {
  26350. var _this = this;
  26351. if (recursive === void 0) { recursive = false; }
  26352. this.meshes.push(newMesh);
  26353. //notify the collision coordinator
  26354. if (this.collisionCoordinator) {
  26355. this.collisionCoordinator.onMeshAdded(newMesh);
  26356. }
  26357. newMesh._resyncLightSources();
  26358. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26359. if (recursive) {
  26360. newMesh.getChildMeshes().forEach(function (m) {
  26361. _this.addMesh(m);
  26362. });
  26363. }
  26364. };
  26365. /**
  26366. * Remove a mesh for the list of scene's meshes
  26367. * @param toRemove defines the mesh to remove
  26368. * @param recursive if all child meshes should also be removed from the scene
  26369. * @returns the index where the mesh was in the mesh list
  26370. */
  26371. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26372. var _this = this;
  26373. if (recursive === void 0) { recursive = false; }
  26374. var index = this.meshes.indexOf(toRemove);
  26375. if (index !== -1) {
  26376. // Remove from the scene if mesh found
  26377. this.meshes.splice(index, 1);
  26378. }
  26379. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26380. if (recursive) {
  26381. toRemove.getChildMeshes().forEach(function (m) {
  26382. _this.removeMesh(m);
  26383. });
  26384. }
  26385. return index;
  26386. };
  26387. /**
  26388. * Add a transform node to the list of scene's transform nodes
  26389. * @param newTransformNode defines the transform node to add
  26390. */
  26391. Scene.prototype.addTransformNode = function (newTransformNode) {
  26392. this.transformNodes.push(newTransformNode);
  26393. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26394. };
  26395. /**
  26396. * Remove a transform node for the list of scene's transform nodes
  26397. * @param toRemove defines the transform node to remove
  26398. * @returns the index where the transform node was in the transform node list
  26399. */
  26400. Scene.prototype.removeTransformNode = function (toRemove) {
  26401. var index = this.transformNodes.indexOf(toRemove);
  26402. if (index !== -1) {
  26403. // Remove from the scene if found
  26404. this.transformNodes.splice(index, 1);
  26405. }
  26406. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26407. return index;
  26408. };
  26409. /**
  26410. * Remove a skeleton for the list of scene's skeletons
  26411. * @param toRemove defines the skeleton to remove
  26412. * @returns the index where the skeleton was in the skeleton list
  26413. */
  26414. Scene.prototype.removeSkeleton = function (toRemove) {
  26415. var index = this.skeletons.indexOf(toRemove);
  26416. if (index !== -1) {
  26417. // Remove from the scene if found
  26418. this.skeletons.splice(index, 1);
  26419. }
  26420. return index;
  26421. };
  26422. /**
  26423. * Remove a morph target for the list of scene's morph targets
  26424. * @param toRemove defines the morph target to remove
  26425. * @returns the index where the morph target was in the morph target list
  26426. */
  26427. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26428. var index = this.morphTargetManagers.indexOf(toRemove);
  26429. if (index !== -1) {
  26430. // Remove from the scene if found
  26431. this.morphTargetManagers.splice(index, 1);
  26432. }
  26433. return index;
  26434. };
  26435. /**
  26436. * Remove a light for the list of scene's lights
  26437. * @param toRemove defines the light to remove
  26438. * @returns the index where the light was in the light list
  26439. */
  26440. Scene.prototype.removeLight = function (toRemove) {
  26441. var index = this.lights.indexOf(toRemove);
  26442. if (index !== -1) {
  26443. // Remove from meshes
  26444. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26445. var mesh = _a[_i];
  26446. mesh._removeLightSource(toRemove);
  26447. }
  26448. // Remove from the scene if mesh found
  26449. this.lights.splice(index, 1);
  26450. this.sortLightsByPriority();
  26451. }
  26452. this.onLightRemovedObservable.notifyObservers(toRemove);
  26453. return index;
  26454. };
  26455. /**
  26456. * Remove a camera for the list of scene's cameras
  26457. * @param toRemove defines the camera to remove
  26458. * @returns the index where the camera was in the camera list
  26459. */
  26460. Scene.prototype.removeCamera = function (toRemove) {
  26461. var index = this.cameras.indexOf(toRemove);
  26462. if (index !== -1) {
  26463. // Remove from the scene if mesh found
  26464. this.cameras.splice(index, 1);
  26465. }
  26466. // Remove from activeCameras
  26467. var index2 = this.activeCameras.indexOf(toRemove);
  26468. if (index2 !== -1) {
  26469. // Remove from the scene if mesh found
  26470. this.activeCameras.splice(index2, 1);
  26471. }
  26472. // Reset the activeCamera
  26473. if (this.activeCamera === toRemove) {
  26474. if (this.cameras.length > 0) {
  26475. this.activeCamera = this.cameras[0];
  26476. }
  26477. else {
  26478. this.activeCamera = null;
  26479. }
  26480. }
  26481. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26482. return index;
  26483. };
  26484. /**
  26485. * Remove a particle system for the list of scene's particle systems
  26486. * @param toRemove defines the particle system to remove
  26487. * @returns the index where the particle system was in the particle system list
  26488. */
  26489. Scene.prototype.removeParticleSystem = function (toRemove) {
  26490. var index = this.particleSystems.indexOf(toRemove);
  26491. if (index !== -1) {
  26492. this.particleSystems.splice(index, 1);
  26493. }
  26494. return index;
  26495. };
  26496. /**
  26497. * Remove a animation for the list of scene's animations
  26498. * @param toRemove defines the animation to remove
  26499. * @returns the index where the animation was in the animation list
  26500. */
  26501. Scene.prototype.removeAnimation = function (toRemove) {
  26502. var index = this.animations.indexOf(toRemove);
  26503. if (index !== -1) {
  26504. this.animations.splice(index, 1);
  26505. }
  26506. return index;
  26507. };
  26508. /**
  26509. * Removes the given animation group from this scene.
  26510. * @param toRemove The animation group to remove
  26511. * @returns The index of the removed animation group
  26512. */
  26513. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26514. var index = this.animationGroups.indexOf(toRemove);
  26515. if (index !== -1) {
  26516. this.animationGroups.splice(index, 1);
  26517. }
  26518. return index;
  26519. };
  26520. /**
  26521. * Removes the given multi-material from this scene.
  26522. * @param toRemove The multi-material to remove
  26523. * @returns The index of the removed multi-material
  26524. */
  26525. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26526. var index = this.multiMaterials.indexOf(toRemove);
  26527. if (index !== -1) {
  26528. this.multiMaterials.splice(index, 1);
  26529. }
  26530. return index;
  26531. };
  26532. /**
  26533. * Removes the given material from this scene.
  26534. * @param toRemove The material to remove
  26535. * @returns The index of the removed material
  26536. */
  26537. Scene.prototype.removeMaterial = function (toRemove) {
  26538. var index = this.materials.indexOf(toRemove);
  26539. if (index !== -1) {
  26540. this.materials.splice(index, 1);
  26541. }
  26542. return index;
  26543. };
  26544. /**
  26545. * Removes the given lens flare system from this scene.
  26546. * @param toRemove The lens flare system to remove
  26547. * @returns The index of the removed lens flare system
  26548. */
  26549. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26550. var index = this.lensFlareSystems.indexOf(toRemove);
  26551. if (index !== -1) {
  26552. this.lensFlareSystems.splice(index, 1);
  26553. }
  26554. return index;
  26555. };
  26556. /**
  26557. * Removes the given action manager from this scene.
  26558. * @param toRemove The action manager to remove
  26559. * @returns The index of the removed action manager
  26560. */
  26561. Scene.prototype.removeActionManager = function (toRemove) {
  26562. var index = this._actionManagers.indexOf(toRemove);
  26563. if (index !== -1) {
  26564. this._actionManagers.splice(index, 1);
  26565. }
  26566. return index;
  26567. };
  26568. /**
  26569. * Removes the given effect layer from this scene.
  26570. * @param toRemove defines the effect layer to remove
  26571. * @returns the index of the removed effect layer
  26572. */
  26573. Scene.prototype.removeEffectLayer = function (toRemove) {
  26574. var index = this.effectLayers.indexOf(toRemove);
  26575. if (index !== -1) {
  26576. this.effectLayers.splice(index, 1);
  26577. }
  26578. return index;
  26579. };
  26580. /**
  26581. * Removes the given texture from this scene.
  26582. * @param toRemove The texture to remove
  26583. * @returns The index of the removed texture
  26584. */
  26585. Scene.prototype.removeTexture = function (toRemove) {
  26586. var index = this.textures.indexOf(toRemove);
  26587. if (index !== -1) {
  26588. this.textures.splice(index, 1);
  26589. }
  26590. return index;
  26591. };
  26592. /**
  26593. * Adds the given light to this scene
  26594. * @param newLight The light to add
  26595. */
  26596. Scene.prototype.addLight = function (newLight) {
  26597. this.lights.push(newLight);
  26598. this.sortLightsByPriority();
  26599. // Add light to all meshes (To support if the light is removed and then readded)
  26600. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26601. var mesh = _a[_i];
  26602. if (mesh._lightSources.indexOf(newLight) === -1) {
  26603. mesh._lightSources.push(newLight);
  26604. mesh._resyncLightSources();
  26605. }
  26606. }
  26607. this.onNewLightAddedObservable.notifyObservers(newLight);
  26608. };
  26609. /**
  26610. * Sorts the list list based on light priorities
  26611. */
  26612. Scene.prototype.sortLightsByPriority = function () {
  26613. if (this.requireLightSorting) {
  26614. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26615. }
  26616. };
  26617. /**
  26618. * Adds the given camera to this scene
  26619. * @param newCamera The camera to add
  26620. */
  26621. Scene.prototype.addCamera = function (newCamera) {
  26622. this.cameras.push(newCamera);
  26623. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26624. };
  26625. /**
  26626. * Adds the given skeleton to this scene
  26627. * @param newSkeleton The skeleton to add
  26628. */
  26629. Scene.prototype.addSkeleton = function (newSkeleton) {
  26630. this.skeletons.push(newSkeleton);
  26631. };
  26632. /**
  26633. * Adds the given particle system to this scene
  26634. * @param newParticleSystem The particle system to add
  26635. */
  26636. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26637. this.particleSystems.push(newParticleSystem);
  26638. };
  26639. /**
  26640. * Adds the given animation to this scene
  26641. * @param newAnimation The animation to add
  26642. */
  26643. Scene.prototype.addAnimation = function (newAnimation) {
  26644. this.animations.push(newAnimation);
  26645. };
  26646. /**
  26647. * Adds the given animation group to this scene.
  26648. * @param newAnimationGroup The animation group to add
  26649. */
  26650. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26651. this.animationGroups.push(newAnimationGroup);
  26652. };
  26653. /**
  26654. * Adds the given multi-material to this scene
  26655. * @param newMultiMaterial The multi-material to add
  26656. */
  26657. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26658. this.multiMaterials.push(newMultiMaterial);
  26659. };
  26660. /**
  26661. * Adds the given material to this scene
  26662. * @param newMaterial The material to add
  26663. */
  26664. Scene.prototype.addMaterial = function (newMaterial) {
  26665. this.materials.push(newMaterial);
  26666. };
  26667. /**
  26668. * Adds the given morph target to this scene
  26669. * @param newMorphTargetManager The morph target to add
  26670. */
  26671. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26672. this.morphTargetManagers.push(newMorphTargetManager);
  26673. };
  26674. /**
  26675. * Adds the given geometry to this scene
  26676. * @param newGeometry The geometry to add
  26677. */
  26678. Scene.prototype.addGeometry = function (newGeometry) {
  26679. this._geometries.push(newGeometry);
  26680. };
  26681. /**
  26682. * Adds the given lens flare system to this scene
  26683. * @param newLensFlareSystem The lens flare system to add
  26684. */
  26685. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26686. this.lensFlareSystems.push(newLensFlareSystem);
  26687. };
  26688. /**
  26689. * Adds the given effect layer to this scene
  26690. * @param newEffectLayer defines the effect layer to add
  26691. */
  26692. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26693. this.effectLayers.push(newEffectLayer);
  26694. };
  26695. /**
  26696. * Adds the given action manager to this scene
  26697. * @param newActionManager The action manager to add
  26698. */
  26699. Scene.prototype.addActionManager = function (newActionManager) {
  26700. this._actionManagers.push(newActionManager);
  26701. };
  26702. /**
  26703. * Adds the given texture to this scene.
  26704. * @param newTexture The texture to add
  26705. */
  26706. Scene.prototype.addTexture = function (newTexture) {
  26707. this.textures.push(newTexture);
  26708. };
  26709. /**
  26710. * Switch active camera
  26711. * @param newCamera defines the new active camera
  26712. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26713. */
  26714. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26715. if (attachControl === void 0) { attachControl = true; }
  26716. var canvas = this._engine.getRenderingCanvas();
  26717. if (!canvas) {
  26718. return;
  26719. }
  26720. if (this.activeCamera) {
  26721. this.activeCamera.detachControl(canvas);
  26722. }
  26723. this.activeCamera = newCamera;
  26724. if (attachControl) {
  26725. newCamera.attachControl(canvas);
  26726. }
  26727. };
  26728. /**
  26729. * sets the active camera of the scene using its ID
  26730. * @param id defines the camera's ID
  26731. * @return the new active camera or null if none found.
  26732. */
  26733. Scene.prototype.setActiveCameraByID = function (id) {
  26734. var camera = this.getCameraByID(id);
  26735. if (camera) {
  26736. this.activeCamera = camera;
  26737. return camera;
  26738. }
  26739. return null;
  26740. };
  26741. /**
  26742. * sets the active camera of the scene using its name
  26743. * @param name defines the camera's name
  26744. * @returns the new active camera or null if none found.
  26745. */
  26746. Scene.prototype.setActiveCameraByName = function (name) {
  26747. var camera = this.getCameraByName(name);
  26748. if (camera) {
  26749. this.activeCamera = camera;
  26750. return camera;
  26751. }
  26752. return null;
  26753. };
  26754. /**
  26755. * get an animation group using its name
  26756. * @param name defines the material's name
  26757. * @return the animation group or null if none found.
  26758. */
  26759. Scene.prototype.getAnimationGroupByName = function (name) {
  26760. for (var index = 0; index < this.animationGroups.length; index++) {
  26761. if (this.animationGroups[index].name === name) {
  26762. return this.animationGroups[index];
  26763. }
  26764. }
  26765. return null;
  26766. };
  26767. /**
  26768. * get a material using its id
  26769. * @param id defines the material's ID
  26770. * @return the material or null if none found.
  26771. */
  26772. Scene.prototype.getMaterialByID = function (id) {
  26773. for (var index = 0; index < this.materials.length; index++) {
  26774. if (this.materials[index].id === id) {
  26775. return this.materials[index];
  26776. }
  26777. }
  26778. return null;
  26779. };
  26780. /**
  26781. * Gets a material using its name
  26782. * @param name defines the material's name
  26783. * @return the material or null if none found.
  26784. */
  26785. Scene.prototype.getMaterialByName = function (name) {
  26786. for (var index = 0; index < this.materials.length; index++) {
  26787. if (this.materials[index].name === name) {
  26788. return this.materials[index];
  26789. }
  26790. }
  26791. return null;
  26792. };
  26793. /**
  26794. * Gets a lens flare system using its name
  26795. * @param name defines the name to look for
  26796. * @returns the lens flare system or null if not found
  26797. */
  26798. Scene.prototype.getLensFlareSystemByName = function (name) {
  26799. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26800. if (this.lensFlareSystems[index].name === name) {
  26801. return this.lensFlareSystems[index];
  26802. }
  26803. }
  26804. return null;
  26805. };
  26806. /**
  26807. * Gets a lens flare system using its id
  26808. * @param id defines the id to look for
  26809. * @returns the lens flare system or null if not found
  26810. */
  26811. Scene.prototype.getLensFlareSystemByID = function (id) {
  26812. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26813. if (this.lensFlareSystems[index].id === id) {
  26814. return this.lensFlareSystems[index];
  26815. }
  26816. }
  26817. return null;
  26818. };
  26819. /**
  26820. * Gets a camera using its id
  26821. * @param id defines the id to look for
  26822. * @returns the camera or null if not found
  26823. */
  26824. Scene.prototype.getCameraByID = function (id) {
  26825. for (var index = 0; index < this.cameras.length; index++) {
  26826. if (this.cameras[index].id === id) {
  26827. return this.cameras[index];
  26828. }
  26829. }
  26830. return null;
  26831. };
  26832. /**
  26833. * Gets a camera using its unique id
  26834. * @param uniqueId defines the unique id to look for
  26835. * @returns the camera or null if not found
  26836. */
  26837. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26838. for (var index = 0; index < this.cameras.length; index++) {
  26839. if (this.cameras[index].uniqueId === uniqueId) {
  26840. return this.cameras[index];
  26841. }
  26842. }
  26843. return null;
  26844. };
  26845. /**
  26846. * Gets a camera using its name
  26847. * @param name defines the camera's name
  26848. * @return the camera or null if none found.
  26849. */
  26850. Scene.prototype.getCameraByName = function (name) {
  26851. for (var index = 0; index < this.cameras.length; index++) {
  26852. if (this.cameras[index].name === name) {
  26853. return this.cameras[index];
  26854. }
  26855. }
  26856. return null;
  26857. };
  26858. /**
  26859. * Gets a bone using its id
  26860. * @param id defines the bone's id
  26861. * @return the bone or null if not found
  26862. */
  26863. Scene.prototype.getBoneByID = function (id) {
  26864. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26865. var skeleton = this.skeletons[skeletonIndex];
  26866. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26867. if (skeleton.bones[boneIndex].id === id) {
  26868. return skeleton.bones[boneIndex];
  26869. }
  26870. }
  26871. }
  26872. return null;
  26873. };
  26874. /**
  26875. * Gets a bone using its id
  26876. * @param name defines the bone's name
  26877. * @return the bone or null if not found
  26878. */
  26879. Scene.prototype.getBoneByName = function (name) {
  26880. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26881. var skeleton = this.skeletons[skeletonIndex];
  26882. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26883. if (skeleton.bones[boneIndex].name === name) {
  26884. return skeleton.bones[boneIndex];
  26885. }
  26886. }
  26887. }
  26888. return null;
  26889. };
  26890. /**
  26891. * Gets a light node using its name
  26892. * @param name defines the the light's name
  26893. * @return the light or null if none found.
  26894. */
  26895. Scene.prototype.getLightByName = function (name) {
  26896. for (var index = 0; index < this.lights.length; index++) {
  26897. if (this.lights[index].name === name) {
  26898. return this.lights[index];
  26899. }
  26900. }
  26901. return null;
  26902. };
  26903. /**
  26904. * Gets a light node using its id
  26905. * @param id defines the light's id
  26906. * @return the light or null if none found.
  26907. */
  26908. Scene.prototype.getLightByID = function (id) {
  26909. for (var index = 0; index < this.lights.length; index++) {
  26910. if (this.lights[index].id === id) {
  26911. return this.lights[index];
  26912. }
  26913. }
  26914. return null;
  26915. };
  26916. /**
  26917. * Gets a light node using its scene-generated unique ID
  26918. * @param uniqueId defines the light's unique id
  26919. * @return the light or null if none found.
  26920. */
  26921. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26922. for (var index = 0; index < this.lights.length; index++) {
  26923. if (this.lights[index].uniqueId === uniqueId) {
  26924. return this.lights[index];
  26925. }
  26926. }
  26927. return null;
  26928. };
  26929. /**
  26930. * Gets a particle system by id
  26931. * @param id defines the particle system id
  26932. * @return the corresponding system or null if none found
  26933. */
  26934. Scene.prototype.getParticleSystemByID = function (id) {
  26935. for (var index = 0; index < this.particleSystems.length; index++) {
  26936. if (this.particleSystems[index].id === id) {
  26937. return this.particleSystems[index];
  26938. }
  26939. }
  26940. return null;
  26941. };
  26942. /**
  26943. * Gets a geometry using its ID
  26944. * @param id defines the geometry's id
  26945. * @return the geometry or null if none found.
  26946. */
  26947. Scene.prototype.getGeometryByID = function (id) {
  26948. for (var index = 0; index < this._geometries.length; index++) {
  26949. if (this._geometries[index].id === id) {
  26950. return this._geometries[index];
  26951. }
  26952. }
  26953. return null;
  26954. };
  26955. /**
  26956. * Add a new geometry to this scene
  26957. * @param geometry defines the geometry to be added to the scene.
  26958. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26959. * @return a boolean defining if the geometry was added or not
  26960. */
  26961. Scene.prototype.pushGeometry = function (geometry, force) {
  26962. if (!force && this.getGeometryByID(geometry.id)) {
  26963. return false;
  26964. }
  26965. this._geometries.push(geometry);
  26966. //notify the collision coordinator
  26967. if (this.collisionCoordinator) {
  26968. this.collisionCoordinator.onGeometryAdded(geometry);
  26969. }
  26970. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26971. return true;
  26972. };
  26973. /**
  26974. * Removes an existing geometry
  26975. * @param geometry defines the geometry to be removed from the scene
  26976. * @return a boolean defining if the geometry was removed or not
  26977. */
  26978. Scene.prototype.removeGeometry = function (geometry) {
  26979. var index = this._geometries.indexOf(geometry);
  26980. if (index > -1) {
  26981. this._geometries.splice(index, 1);
  26982. //notify the collision coordinator
  26983. if (this.collisionCoordinator) {
  26984. this.collisionCoordinator.onGeometryDeleted(geometry);
  26985. }
  26986. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26987. return true;
  26988. }
  26989. return false;
  26990. };
  26991. /**
  26992. * Gets the list of geometries attached to the scene
  26993. * @returns an array of Geometry
  26994. */
  26995. Scene.prototype.getGeometries = function () {
  26996. return this._geometries;
  26997. };
  26998. /**
  26999. * Gets the first added mesh found of a given ID
  27000. * @param id defines the id to search for
  27001. * @return the mesh found or null if not found at all
  27002. */
  27003. Scene.prototype.getMeshByID = function (id) {
  27004. for (var index = 0; index < this.meshes.length; index++) {
  27005. if (this.meshes[index].id === id) {
  27006. return this.meshes[index];
  27007. }
  27008. }
  27009. return null;
  27010. };
  27011. /**
  27012. * Gets a list of meshes using their id
  27013. * @param id defines the id to search for
  27014. * @returns a list of meshes
  27015. */
  27016. Scene.prototype.getMeshesByID = function (id) {
  27017. return this.meshes.filter(function (m) {
  27018. return m.id === id;
  27019. });
  27020. };
  27021. /**
  27022. * Gets the first added transform node found of a given ID
  27023. * @param id defines the id to search for
  27024. * @return the found transform node or null if not found at all.
  27025. */
  27026. Scene.prototype.getTransformNodeByID = function (id) {
  27027. for (var index = 0; index < this.transformNodes.length; index++) {
  27028. if (this.transformNodes[index].id === id) {
  27029. return this.transformNodes[index];
  27030. }
  27031. }
  27032. return null;
  27033. };
  27034. /**
  27035. * Gets a list of transform nodes using their id
  27036. * @param id defines the id to search for
  27037. * @returns a list of transform nodes
  27038. */
  27039. Scene.prototype.getTransformNodesByID = function (id) {
  27040. return this.transformNodes.filter(function (m) {
  27041. return m.id === id;
  27042. });
  27043. };
  27044. /**
  27045. * Gets a mesh with its auto-generated unique id
  27046. * @param uniqueId defines the unique id to search for
  27047. * @return the found mesh or null if not found at all.
  27048. */
  27049. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27050. for (var index = 0; index < this.meshes.length; index++) {
  27051. if (this.meshes[index].uniqueId === uniqueId) {
  27052. return this.meshes[index];
  27053. }
  27054. }
  27055. return null;
  27056. };
  27057. /**
  27058. * Gets a the last added mesh using a given id
  27059. * @param id defines the id to search for
  27060. * @return the found mesh or null if not found at all.
  27061. */
  27062. Scene.prototype.getLastMeshByID = function (id) {
  27063. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27064. if (this.meshes[index].id === id) {
  27065. return this.meshes[index];
  27066. }
  27067. }
  27068. return null;
  27069. };
  27070. /**
  27071. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27072. * @param id defines the id to search for
  27073. * @return the found node or null if not found at all
  27074. */
  27075. Scene.prototype.getLastEntryByID = function (id) {
  27076. var index;
  27077. for (index = this.meshes.length - 1; index >= 0; index--) {
  27078. if (this.meshes[index].id === id) {
  27079. return this.meshes[index];
  27080. }
  27081. }
  27082. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27083. if (this.transformNodes[index].id === id) {
  27084. return this.transformNodes[index];
  27085. }
  27086. }
  27087. for (index = this.cameras.length - 1; index >= 0; index--) {
  27088. if (this.cameras[index].id === id) {
  27089. return this.cameras[index];
  27090. }
  27091. }
  27092. for (index = this.lights.length - 1; index >= 0; index--) {
  27093. if (this.lights[index].id === id) {
  27094. return this.lights[index];
  27095. }
  27096. }
  27097. return null;
  27098. };
  27099. /**
  27100. * Gets a node (Mesh, Camera, Light) using a given id
  27101. * @param id defines the id to search for
  27102. * @return the found node or null if not found at all
  27103. */
  27104. Scene.prototype.getNodeByID = function (id) {
  27105. var mesh = this.getMeshByID(id);
  27106. if (mesh) {
  27107. return mesh;
  27108. }
  27109. var light = this.getLightByID(id);
  27110. if (light) {
  27111. return light;
  27112. }
  27113. var camera = this.getCameraByID(id);
  27114. if (camera) {
  27115. return camera;
  27116. }
  27117. var bone = this.getBoneByID(id);
  27118. return bone;
  27119. };
  27120. /**
  27121. * Gets a node (Mesh, Camera, Light) using a given name
  27122. * @param name defines the name to search for
  27123. * @return the found node or null if not found at all.
  27124. */
  27125. Scene.prototype.getNodeByName = function (name) {
  27126. var mesh = this.getMeshByName(name);
  27127. if (mesh) {
  27128. return mesh;
  27129. }
  27130. var light = this.getLightByName(name);
  27131. if (light) {
  27132. return light;
  27133. }
  27134. var camera = this.getCameraByName(name);
  27135. if (camera) {
  27136. return camera;
  27137. }
  27138. var bone = this.getBoneByName(name);
  27139. return bone;
  27140. };
  27141. /**
  27142. * Gets a mesh using a given name
  27143. * @param name defines the name to search for
  27144. * @return the found mesh or null if not found at all.
  27145. */
  27146. Scene.prototype.getMeshByName = function (name) {
  27147. for (var index = 0; index < this.meshes.length; index++) {
  27148. if (this.meshes[index].name === name) {
  27149. return this.meshes[index];
  27150. }
  27151. }
  27152. return null;
  27153. };
  27154. /**
  27155. * Gets a transform node using a given name
  27156. * @param name defines the name to search for
  27157. * @return the found transform node or null if not found at all.
  27158. */
  27159. Scene.prototype.getTransformNodeByName = function (name) {
  27160. for (var index = 0; index < this.transformNodes.length; index++) {
  27161. if (this.transformNodes[index].name === name) {
  27162. return this.transformNodes[index];
  27163. }
  27164. }
  27165. return null;
  27166. };
  27167. /**
  27168. * Gets a sound using a given name
  27169. * @param name defines the name to search for
  27170. * @return the found sound or null if not found at all.
  27171. */
  27172. Scene.prototype.getSoundByName = function (name) {
  27173. var index;
  27174. if (BABYLON.AudioEngine) {
  27175. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27176. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27177. return this.mainSoundTrack.soundCollection[index];
  27178. }
  27179. }
  27180. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27181. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27182. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27183. return this.soundTracks[sdIndex].soundCollection[index];
  27184. }
  27185. }
  27186. }
  27187. }
  27188. return null;
  27189. };
  27190. /**
  27191. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27192. * @param id defines the id to search for
  27193. * @return the found skeleton or null if not found at all.
  27194. */
  27195. Scene.prototype.getLastSkeletonByID = function (id) {
  27196. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27197. if (this.skeletons[index].id === id) {
  27198. return this.skeletons[index];
  27199. }
  27200. }
  27201. return null;
  27202. };
  27203. /**
  27204. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27205. * @param id defines the id to search for
  27206. * @return the found skeleton or null if not found at all.
  27207. */
  27208. Scene.prototype.getSkeletonById = function (id) {
  27209. for (var index = 0; index < this.skeletons.length; index++) {
  27210. if (this.skeletons[index].id === id) {
  27211. return this.skeletons[index];
  27212. }
  27213. }
  27214. return null;
  27215. };
  27216. /**
  27217. * Gets a skeleton using a given name
  27218. * @param name defines the name to search for
  27219. * @return the found skeleton or null if not found at all.
  27220. */
  27221. Scene.prototype.getSkeletonByName = function (name) {
  27222. for (var index = 0; index < this.skeletons.length; index++) {
  27223. if (this.skeletons[index].name === name) {
  27224. return this.skeletons[index];
  27225. }
  27226. }
  27227. return null;
  27228. };
  27229. /**
  27230. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27231. * @param id defines the id to search for
  27232. * @return the found morph target manager or null if not found at all.
  27233. */
  27234. Scene.prototype.getMorphTargetManagerById = function (id) {
  27235. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27236. if (this.morphTargetManagers[index].uniqueId === id) {
  27237. return this.morphTargetManagers[index];
  27238. }
  27239. }
  27240. return null;
  27241. };
  27242. /**
  27243. * Gets a boolean indicating if the given mesh is active
  27244. * @param mesh defines the mesh to look for
  27245. * @returns true if the mesh is in the active list
  27246. */
  27247. Scene.prototype.isActiveMesh = function (mesh) {
  27248. return (this._activeMeshes.indexOf(mesh) !== -1);
  27249. };
  27250. /**
  27251. * Return a the first highlight layer of the scene with a given name.
  27252. * @param name The name of the highlight layer to look for.
  27253. * @return The highlight layer if found otherwise null.
  27254. */
  27255. Scene.prototype.getHighlightLayerByName = function (name) {
  27256. for (var index = 0; index < this.effectLayers.length; index++) {
  27257. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27258. return this.effectLayers[index];
  27259. }
  27260. }
  27261. return null;
  27262. };
  27263. /**
  27264. * Return a the first highlight layer of the scene with a given name.
  27265. * @param name The name of the highlight layer to look for.
  27266. * @return The highlight layer if found otherwise null.
  27267. */
  27268. Scene.prototype.getGlowLayerByName = function (name) {
  27269. for (var index = 0; index < this.effectLayers.length; index++) {
  27270. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27271. return this.effectLayers[index];
  27272. }
  27273. }
  27274. return null;
  27275. };
  27276. Object.defineProperty(Scene.prototype, "uid", {
  27277. /**
  27278. * Return a unique id as a string which can serve as an identifier for the scene
  27279. */
  27280. get: function () {
  27281. if (!this._uid) {
  27282. this._uid = BABYLON.Tools.RandomId();
  27283. }
  27284. return this._uid;
  27285. },
  27286. enumerable: true,
  27287. configurable: true
  27288. });
  27289. /**
  27290. * Add an externaly attached data from its key.
  27291. * This method call will fail and return false, if such key already exists.
  27292. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27293. * @param key the unique key that identifies the data
  27294. * @param data the data object to associate to the key for this Engine instance
  27295. * @return true if no such key were already present and the data was added successfully, false otherwise
  27296. */
  27297. Scene.prototype.addExternalData = function (key, data) {
  27298. if (!this._externalData) {
  27299. this._externalData = new BABYLON.StringDictionary();
  27300. }
  27301. return this._externalData.add(key, data);
  27302. };
  27303. /**
  27304. * Get an externaly attached data from its key
  27305. * @param key the unique key that identifies the data
  27306. * @return the associated data, if present (can be null), or undefined if not present
  27307. */
  27308. Scene.prototype.getExternalData = function (key) {
  27309. if (!this._externalData) {
  27310. return null;
  27311. }
  27312. return this._externalData.get(key);
  27313. };
  27314. /**
  27315. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27316. * @param key the unique key that identifies the data
  27317. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27318. * @return the associated data, can be null if the factory returned null.
  27319. */
  27320. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27321. if (!this._externalData) {
  27322. this._externalData = new BABYLON.StringDictionary();
  27323. }
  27324. return this._externalData.getOrAddWithFactory(key, factory);
  27325. };
  27326. /**
  27327. * Remove an externaly attached data from the Engine instance
  27328. * @param key the unique key that identifies the data
  27329. * @return true if the data was successfully removed, false if it doesn't exist
  27330. */
  27331. Scene.prototype.removeExternalData = function (key) {
  27332. return this._externalData.remove(key);
  27333. };
  27334. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27335. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27336. if (mesh.showSubMeshesBoundingBox) {
  27337. var boundingInfo = subMesh.getBoundingInfo();
  27338. if (boundingInfo !== null && boundingInfo !== undefined) {
  27339. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27340. }
  27341. }
  27342. var material = subMesh.getMaterial();
  27343. if (material !== null && material !== undefined) {
  27344. // Render targets
  27345. if (material.getRenderTargetTextures !== undefined) {
  27346. if (this._processedMaterials.indexOf(material) === -1) {
  27347. this._processedMaterials.push(material);
  27348. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27349. }
  27350. }
  27351. // Dispatch
  27352. this._activeIndices.addCount(subMesh.indexCount, false);
  27353. this._renderingManager.dispatch(subMesh, mesh, material);
  27354. }
  27355. }
  27356. };
  27357. /**
  27358. * Clear the processed materials smart array preventing retention point in material dispose.
  27359. */
  27360. Scene.prototype.freeProcessedMaterials = function () {
  27361. this._processedMaterials.dispose();
  27362. };
  27363. /**
  27364. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27365. */
  27366. Scene.prototype.freeActiveMeshes = function () {
  27367. this._activeMeshes.dispose();
  27368. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27369. this.activeCamera._activeMeshes.dispose();
  27370. }
  27371. if (this.activeCameras) {
  27372. for (var i = 0; i < this.activeCameras.length; i++) {
  27373. var activeCamera = this.activeCameras[i];
  27374. if (activeCamera && activeCamera._activeMeshes) {
  27375. activeCamera._activeMeshes.dispose();
  27376. }
  27377. }
  27378. }
  27379. };
  27380. /**
  27381. * Clear the info related to rendering groups preventing retention points during dispose.
  27382. */
  27383. Scene.prototype.freeRenderingGroups = function () {
  27384. if (this._renderingManager) {
  27385. this._renderingManager.freeRenderingGroups();
  27386. }
  27387. if (this.textures) {
  27388. for (var i = 0; i < this.textures.length; i++) {
  27389. var texture = this.textures[i];
  27390. if (texture && texture.renderList) {
  27391. texture.freeRenderingGroups();
  27392. }
  27393. }
  27394. }
  27395. };
  27396. /** @hidden */
  27397. Scene.prototype._isInIntermediateRendering = function () {
  27398. return this._intermediateRendering;
  27399. };
  27400. /**
  27401. * Defines the current active mesh candidate provider
  27402. * @param provider defines the provider to use
  27403. */
  27404. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27405. this._activeMeshCandidateProvider = provider;
  27406. };
  27407. /**
  27408. * Gets the current active mesh candidate provider
  27409. * @returns the current active mesh candidate provider
  27410. */
  27411. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27412. return this._activeMeshCandidateProvider;
  27413. };
  27414. /**
  27415. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27416. * @returns the current scene
  27417. */
  27418. Scene.prototype.freezeActiveMeshes = function () {
  27419. if (!this.activeCamera) {
  27420. return this;
  27421. }
  27422. if (!this._frustumPlanes) {
  27423. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27424. }
  27425. this._evaluateActiveMeshes();
  27426. this._activeMeshesFrozen = true;
  27427. return this;
  27428. };
  27429. /**
  27430. * Use this function to restart evaluating active meshes on every frame
  27431. * @returns the current scene
  27432. */
  27433. Scene.prototype.unfreezeActiveMeshes = function () {
  27434. this._activeMeshesFrozen = false;
  27435. return this;
  27436. };
  27437. Scene.prototype._evaluateActiveMeshes = function () {
  27438. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27439. return;
  27440. }
  27441. if (!this.activeCamera) {
  27442. return;
  27443. }
  27444. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27445. this.activeCamera._activeMeshes.reset();
  27446. this._activeMeshes.reset();
  27447. this._renderingManager.reset();
  27448. this._processedMaterials.reset();
  27449. this._activeParticleSystems.reset();
  27450. this._activeSkeletons.reset();
  27451. this._softwareSkinnedMeshes.reset();
  27452. if (this._boundingBoxRenderer) {
  27453. this._boundingBoxRenderer.reset();
  27454. }
  27455. // Meshes
  27456. var meshes;
  27457. var len;
  27458. var checkIsEnabled = true;
  27459. // Determine mesh candidates
  27460. if (this._activeMeshCandidateProvider !== undefined) {
  27461. // Use _activeMeshCandidateProvider
  27462. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27463. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27464. if (meshes !== undefined) {
  27465. len = meshes.length;
  27466. }
  27467. else {
  27468. len = 0;
  27469. }
  27470. }
  27471. else if (this._selectionOctree !== undefined) {
  27472. // Octree
  27473. var selection = this._selectionOctree.select(this._frustumPlanes);
  27474. meshes = selection.data;
  27475. len = selection.length;
  27476. }
  27477. else {
  27478. // Full scene traversal
  27479. len = this.meshes.length;
  27480. meshes = this.meshes;
  27481. }
  27482. // Check each mesh
  27483. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27484. mesh = meshes[meshIndex];
  27485. if (mesh.isBlocked) {
  27486. continue;
  27487. }
  27488. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27489. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27490. continue;
  27491. }
  27492. mesh.computeWorldMatrix();
  27493. // Intersections
  27494. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27495. this._meshesForIntersections.pushNoDuplicate(mesh);
  27496. }
  27497. // Switch to current LOD
  27498. meshLOD = mesh.getLOD(this.activeCamera);
  27499. if (meshLOD === undefined || meshLOD === null) {
  27500. continue;
  27501. }
  27502. mesh._preActivate();
  27503. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27504. this._activeMeshes.push(mesh);
  27505. this.activeCamera._activeMeshes.push(mesh);
  27506. mesh._activate(this._renderId);
  27507. if (meshLOD !== mesh) {
  27508. meshLOD._activate(this._renderId);
  27509. }
  27510. this._activeMesh(mesh, meshLOD);
  27511. }
  27512. }
  27513. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27514. // Particle systems
  27515. if (this.particlesEnabled) {
  27516. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27517. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27518. var particleSystem = this.particleSystems[particleIndex];
  27519. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27520. continue;
  27521. }
  27522. var emitter = particleSystem.emitter;
  27523. if (!emitter.position || emitter.isEnabled()) {
  27524. this._activeParticleSystems.push(particleSystem);
  27525. particleSystem.animate();
  27526. this._renderingManager.dispatchParticles(particleSystem);
  27527. }
  27528. }
  27529. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27530. }
  27531. };
  27532. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27533. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27534. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27535. mesh.skeleton.prepare();
  27536. }
  27537. if (!mesh.computeBonesUsingShaders) {
  27538. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27539. }
  27540. }
  27541. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27542. var boundingInfo = sourceMesh.getBoundingInfo();
  27543. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27544. }
  27545. if (mesh !== undefined && mesh !== null
  27546. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27547. // Submeshes Octrees
  27548. var len;
  27549. var subMeshes;
  27550. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27551. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27552. len = intersections.length;
  27553. subMeshes = intersections.data;
  27554. }
  27555. else {
  27556. subMeshes = mesh.subMeshes;
  27557. len = subMeshes.length;
  27558. }
  27559. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27560. subMesh = subMeshes[subIndex];
  27561. this._evaluateSubMesh(subMesh, mesh);
  27562. }
  27563. }
  27564. };
  27565. /**
  27566. * Update the transform matrix to update from the current active camera
  27567. * @param force defines a boolean used to force the update even if cache is up to date
  27568. */
  27569. Scene.prototype.updateTransformMatrix = function (force) {
  27570. if (!this.activeCamera) {
  27571. return;
  27572. }
  27573. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27574. };
  27575. /**
  27576. * 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)
  27577. * @param alternateCamera defines the camera to use
  27578. */
  27579. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27580. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27581. };
  27582. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27583. if (camera && camera._skipRendering) {
  27584. return;
  27585. }
  27586. var engine = this._engine;
  27587. this.activeCamera = camera;
  27588. if (!this.activeCamera)
  27589. throw new Error("Active camera not set");
  27590. // Viewport
  27591. engine.setViewport(this.activeCamera.viewport);
  27592. // Camera
  27593. this.resetCachedMaterial();
  27594. this._renderId++;
  27595. this.updateTransformMatrix();
  27596. if (camera._alternateCamera) {
  27597. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27598. this._alternateRendering = true;
  27599. }
  27600. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27601. // Meshes
  27602. this._evaluateActiveMeshes();
  27603. // Software skinning
  27604. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27605. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27606. mesh.applySkeleton(mesh.skeleton);
  27607. }
  27608. // Render targets
  27609. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27610. var needsRestoreFrameBuffer = false;
  27611. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27612. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27613. }
  27614. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27615. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27616. }
  27617. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27618. this._intermediateRendering = true;
  27619. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27620. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27621. var renderTarget = this._renderTargets.data[renderIndex];
  27622. if (renderTarget._shouldRender()) {
  27623. this._renderId++;
  27624. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27625. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27626. }
  27627. }
  27628. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27629. this._intermediateRendering = false;
  27630. this._renderId++;
  27631. needsRestoreFrameBuffer = true; // Restore back buffer
  27632. }
  27633. // Render EffectLayer Texture
  27634. var stencilState = this._engine.getStencilBuffer();
  27635. var renderEffects = false;
  27636. var needStencil = false;
  27637. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27638. this._intermediateRendering = true;
  27639. for (var i = 0; i < this.effectLayers.length; i++) {
  27640. var effectLayer = this.effectLayers[i];
  27641. if (effectLayer.shouldRender() &&
  27642. (!effectLayer.camera ||
  27643. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27644. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27645. renderEffects = true;
  27646. needStencil = needStencil || effectLayer.needStencil();
  27647. var renderTarget = effectLayer._mainTexture;
  27648. if (renderTarget._shouldRender()) {
  27649. this._renderId++;
  27650. renderTarget.render(false, false);
  27651. needsRestoreFrameBuffer = true;
  27652. }
  27653. }
  27654. }
  27655. this._intermediateRendering = false;
  27656. this._renderId++;
  27657. }
  27658. if (needsRestoreFrameBuffer) {
  27659. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27660. }
  27661. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27662. // Prepare Frame
  27663. if (this.postProcessManager) {
  27664. this.postProcessManager._prepareFrame();
  27665. }
  27666. // Backgrounds
  27667. var layerIndex;
  27668. var layer;
  27669. if (this.layers.length) {
  27670. engine.setDepthBuffer(false);
  27671. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27672. layer = this.layers[layerIndex];
  27673. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27674. layer.render();
  27675. }
  27676. }
  27677. engine.setDepthBuffer(true);
  27678. }
  27679. // Activate effect Layer stencil
  27680. if (needStencil) {
  27681. this._engine.setStencilBuffer(true);
  27682. }
  27683. // Render
  27684. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27685. this._renderingManager.render(null, null, true, true);
  27686. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27687. // Restore effect Layer stencil
  27688. if (needStencil) {
  27689. this._engine.setStencilBuffer(stencilState);
  27690. }
  27691. // Bounding boxes
  27692. if (this._boundingBoxRenderer) {
  27693. this._boundingBoxRenderer.render();
  27694. }
  27695. // Lens flares
  27696. if (this.lensFlaresEnabled) {
  27697. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27698. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27699. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27700. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27701. lensFlareSystem.render();
  27702. }
  27703. }
  27704. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27705. }
  27706. // Effect Layer
  27707. if (renderEffects) {
  27708. engine.setDepthBuffer(false);
  27709. for (var i = 0; i < this.effectLayers.length; i++) {
  27710. if (this.effectLayers[i].shouldRender()) {
  27711. this.effectLayers[i].render();
  27712. }
  27713. }
  27714. engine.setDepthBuffer(true);
  27715. }
  27716. // Foregrounds
  27717. if (this.layers.length) {
  27718. engine.setDepthBuffer(false);
  27719. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27720. layer = this.layers[layerIndex];
  27721. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27722. layer.render();
  27723. }
  27724. }
  27725. engine.setDepthBuffer(true);
  27726. }
  27727. // Finalize frame
  27728. if (this.postProcessManager) {
  27729. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27730. }
  27731. // Reset some special arrays
  27732. this._renderTargets.reset();
  27733. this._alternateRendering = false;
  27734. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27735. };
  27736. Scene.prototype._processSubCameras = function (camera) {
  27737. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27738. this._renderForCamera(camera);
  27739. return;
  27740. }
  27741. // rig cameras
  27742. for (var index = 0; index < camera._rigCameras.length; index++) {
  27743. this._renderForCamera(camera._rigCameras[index], camera);
  27744. }
  27745. this.activeCamera = camera;
  27746. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27747. };
  27748. Scene.prototype._checkIntersections = function () {
  27749. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27750. var sourceMesh = this._meshesForIntersections.data[index];
  27751. if (!sourceMesh.actionManager) {
  27752. continue;
  27753. }
  27754. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27755. var action = sourceMesh.actionManager.actions[actionIndex];
  27756. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27757. var parameters = action.getTriggerParameter();
  27758. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27759. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27760. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27761. if (areIntersecting && currentIntersectionInProgress === -1) {
  27762. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27763. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27764. sourceMesh._intersectionsInProgress.push(otherMesh);
  27765. }
  27766. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27767. sourceMesh._intersectionsInProgress.push(otherMesh);
  27768. }
  27769. }
  27770. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27771. //They intersected, and now they don't.
  27772. //is this trigger an exit trigger? execute an event.
  27773. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27774. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27775. }
  27776. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27777. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27778. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27779. return otherMesh === parameterMesh;
  27780. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27781. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27782. }
  27783. }
  27784. }
  27785. }
  27786. }
  27787. };
  27788. /**
  27789. * Render the scene
  27790. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27791. */
  27792. Scene.prototype.render = function (updateCameras) {
  27793. if (updateCameras === void 0) { updateCameras = true; }
  27794. if (this.isDisposed) {
  27795. return;
  27796. }
  27797. this._activeParticles.fetchNewFrame();
  27798. this._totalVertices.fetchNewFrame();
  27799. this._activeIndices.fetchNewFrame();
  27800. this._activeBones.fetchNewFrame();
  27801. this._meshesForIntersections.reset();
  27802. this.resetCachedMaterial();
  27803. this.onBeforeAnimationsObservable.notifyObservers(this);
  27804. // Actions
  27805. if (this.actionManager) {
  27806. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27807. }
  27808. //Simplification Queue
  27809. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27810. this.simplificationQueue.executeNext();
  27811. }
  27812. if (this._engine.isDeterministicLockStep()) {
  27813. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27814. var defaultFPS = (60.0 / 1000.0);
  27815. var defaultFrameTime = 1000 / 60; // frame time in MS
  27816. if (this._physicsEngine) {
  27817. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27818. }
  27819. var stepsTaken = 0;
  27820. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27821. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27822. internalSteps = Math.min(internalSteps, maxSubSteps);
  27823. do {
  27824. this.onBeforeStepObservable.notifyObservers(this);
  27825. // Animations
  27826. this._animationRatio = defaultFrameTime * defaultFPS;
  27827. this._animate();
  27828. this.onAfterAnimationsObservable.notifyObservers(this);
  27829. // Physics
  27830. if (this._physicsEngine) {
  27831. this.onBeforePhysicsObservable.notifyObservers(this);
  27832. this._physicsEngine._step(defaultFrameTime / 1000);
  27833. this.onAfterPhysicsObservable.notifyObservers(this);
  27834. }
  27835. this.onAfterStepObservable.notifyObservers(this);
  27836. this._currentStepId++;
  27837. stepsTaken++;
  27838. deltaTime -= defaultFrameTime;
  27839. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27840. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27841. }
  27842. else {
  27843. // Animations
  27844. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27845. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27846. this._animate();
  27847. this.onAfterAnimationsObservable.notifyObservers(this);
  27848. // Physics
  27849. if (this._physicsEngine) {
  27850. this.onBeforePhysicsObservable.notifyObservers(this);
  27851. this._physicsEngine._step(deltaTime / 1000.0);
  27852. this.onAfterPhysicsObservable.notifyObservers(this);
  27853. }
  27854. }
  27855. // update gamepad manager
  27856. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27857. this._gamepadManager._checkGamepadsStatus();
  27858. }
  27859. // Update Cameras
  27860. if (updateCameras) {
  27861. if (this.activeCameras.length > 0) {
  27862. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27863. var camera = this.activeCameras[cameraIndex];
  27864. camera.update();
  27865. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27866. // rig cameras
  27867. for (var index = 0; index < camera._rigCameras.length; index++) {
  27868. camera._rigCameras[index].update();
  27869. }
  27870. }
  27871. }
  27872. }
  27873. else if (this.activeCamera) {
  27874. this.activeCamera.update();
  27875. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27876. // rig cameras
  27877. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27878. this.activeCamera._rigCameras[index].update();
  27879. }
  27880. }
  27881. }
  27882. }
  27883. // Before render
  27884. this.onBeforeRenderObservable.notifyObservers(this);
  27885. // Customs render targets
  27886. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27887. var engine = this.getEngine();
  27888. var currentActiveCamera = this.activeCamera;
  27889. if (this.renderTargetsEnabled) {
  27890. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27891. this._intermediateRendering = true;
  27892. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27893. var renderTarget = this.customRenderTargets[customIndex];
  27894. if (renderTarget._shouldRender()) {
  27895. this._renderId++;
  27896. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27897. if (!this.activeCamera)
  27898. throw new Error("Active camera not set");
  27899. // Viewport
  27900. engine.setViewport(this.activeCamera.viewport);
  27901. // Camera
  27902. this.updateTransformMatrix();
  27903. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27904. }
  27905. }
  27906. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27907. this._intermediateRendering = false;
  27908. this._renderId++;
  27909. }
  27910. // Restore back buffer
  27911. if (this.customRenderTargets.length > 0) {
  27912. engine.restoreDefaultFramebuffer();
  27913. }
  27914. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27915. this.activeCamera = currentActiveCamera;
  27916. // Procedural textures
  27917. if (this.proceduralTexturesEnabled) {
  27918. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27919. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27920. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27921. if (proceduralTexture._shouldRender()) {
  27922. proceduralTexture.render();
  27923. }
  27924. }
  27925. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27926. }
  27927. // Clear
  27928. if (this.autoClearDepthAndStencil || this.autoClear) {
  27929. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27930. }
  27931. // Shadows
  27932. if (this.shadowsEnabled) {
  27933. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27934. var light = this.lights[lightIndex];
  27935. var shadowGenerator = light.getShadowGenerator();
  27936. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27937. var shadowMap = (shadowGenerator.getShadowMap());
  27938. if (this.textures.indexOf(shadowMap) !== -1) {
  27939. this._renderTargets.push(shadowMap);
  27940. }
  27941. }
  27942. }
  27943. }
  27944. // Depth renderer
  27945. for (var key in this._depthRenderer) {
  27946. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27947. }
  27948. // Geometry renderer
  27949. if (this._geometryBufferRenderer) {
  27950. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27951. }
  27952. // RenderPipeline
  27953. if (this._postProcessRenderPipelineManager) {
  27954. this._postProcessRenderPipelineManager.update();
  27955. }
  27956. // Multi-cameras?
  27957. if (this.activeCameras.length > 0) {
  27958. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27959. if (cameraIndex > 0) {
  27960. this._engine.clear(null, false, true, true);
  27961. }
  27962. this._processSubCameras(this.activeCameras[cameraIndex]);
  27963. }
  27964. }
  27965. else {
  27966. if (!this.activeCamera) {
  27967. throw new Error("No camera defined");
  27968. }
  27969. this._processSubCameras(this.activeCamera);
  27970. }
  27971. // Intersection checks
  27972. this._checkIntersections();
  27973. // Update the audio listener attached to the camera
  27974. if (BABYLON.AudioEngine) {
  27975. this._updateAudioParameters();
  27976. }
  27977. // After render
  27978. if (this.afterRender) {
  27979. this.afterRender();
  27980. }
  27981. this.onAfterRenderObservable.notifyObservers(this);
  27982. // Cleaning
  27983. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27984. var data = this._toBeDisposed.data[index];
  27985. if (data) {
  27986. data.dispose();
  27987. }
  27988. this._toBeDisposed[index] = null;
  27989. }
  27990. this._toBeDisposed.reset();
  27991. if (this.dumpNextRenderTargets) {
  27992. this.dumpNextRenderTargets = false;
  27993. }
  27994. this._activeBones.addCount(0, true);
  27995. this._activeIndices.addCount(0, true);
  27996. this._activeParticles.addCount(0, true);
  27997. };
  27998. Scene.prototype._updateAudioParameters = function () {
  27999. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  28000. return;
  28001. }
  28002. var listeningCamera;
  28003. var audioEngine = BABYLON.Engine.audioEngine;
  28004. if (this.activeCameras.length > 0) {
  28005. listeningCamera = this.activeCameras[0];
  28006. }
  28007. else {
  28008. listeningCamera = this.activeCamera;
  28009. }
  28010. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  28011. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  28012. // for VR cameras
  28013. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  28014. listeningCamera = listeningCamera.rigCameras[0];
  28015. }
  28016. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  28017. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  28018. cameraDirection.normalize();
  28019. // To avoid some errors on GearVR
  28020. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  28021. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  28022. }
  28023. var i;
  28024. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28025. var sound = this.mainSoundTrack.soundCollection[i];
  28026. if (sound.useCustomAttenuation) {
  28027. sound.updateDistanceFromListener();
  28028. }
  28029. }
  28030. for (i = 0; i < this.soundTracks.length; i++) {
  28031. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28032. sound = this.soundTracks[i].soundCollection[j];
  28033. if (sound.useCustomAttenuation) {
  28034. sound.updateDistanceFromListener();
  28035. }
  28036. }
  28037. }
  28038. }
  28039. };
  28040. Object.defineProperty(Scene.prototype, "audioEnabled", {
  28041. // Audio
  28042. /**
  28043. * Gets or sets if audio support is enabled
  28044. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28045. */
  28046. get: function () {
  28047. return this._audioEnabled;
  28048. },
  28049. set: function (value) {
  28050. this._audioEnabled = value;
  28051. if (BABYLON.AudioEngine) {
  28052. if (this._audioEnabled) {
  28053. this._enableAudio();
  28054. }
  28055. else {
  28056. this._disableAudio();
  28057. }
  28058. }
  28059. },
  28060. enumerable: true,
  28061. configurable: true
  28062. });
  28063. Scene.prototype._disableAudio = function () {
  28064. var i;
  28065. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28066. this.mainSoundTrack.soundCollection[i].pause();
  28067. }
  28068. for (i = 0; i < this.soundTracks.length; i++) {
  28069. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28070. this.soundTracks[i].soundCollection[j].pause();
  28071. }
  28072. }
  28073. };
  28074. Scene.prototype._enableAudio = function () {
  28075. var i;
  28076. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28077. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28078. this.mainSoundTrack.soundCollection[i].play();
  28079. }
  28080. }
  28081. for (i = 0; i < this.soundTracks.length; i++) {
  28082. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28083. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28084. this.soundTracks[i].soundCollection[j].play();
  28085. }
  28086. }
  28087. }
  28088. };
  28089. Object.defineProperty(Scene.prototype, "headphone", {
  28090. /**
  28091. * Gets or sets if audio will be output to headphones
  28092. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28093. */
  28094. get: function () {
  28095. return this._headphone;
  28096. },
  28097. set: function (value) {
  28098. this._headphone = value;
  28099. if (BABYLON.AudioEngine) {
  28100. if (this._headphone) {
  28101. this._switchAudioModeForHeadphones();
  28102. }
  28103. else {
  28104. this._switchAudioModeForNormalSpeakers();
  28105. }
  28106. }
  28107. },
  28108. enumerable: true,
  28109. configurable: true
  28110. });
  28111. Scene.prototype._switchAudioModeForHeadphones = function () {
  28112. this.mainSoundTrack.switchPanningModelToHRTF();
  28113. for (var i = 0; i < this.soundTracks.length; i++) {
  28114. this.soundTracks[i].switchPanningModelToHRTF();
  28115. }
  28116. };
  28117. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28118. this.mainSoundTrack.switchPanningModelToEqualPower();
  28119. for (var i = 0; i < this.soundTracks.length; i++) {
  28120. this.soundTracks[i].switchPanningModelToEqualPower();
  28121. }
  28122. };
  28123. /**
  28124. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  28125. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  28126. * @returns the created depth renderer
  28127. */
  28128. Scene.prototype.enableDepthRenderer = function (camera) {
  28129. camera = camera || this.activeCamera;
  28130. if (!camera) {
  28131. throw "No camera available to enable depth renderer";
  28132. }
  28133. if (!this._depthRenderer[camera.id]) {
  28134. var textureType = 0;
  28135. if (this._engine.getCaps().textureHalfFloatRender) {
  28136. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  28137. }
  28138. else if (this._engine.getCaps().textureFloatRender) {
  28139. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28140. }
  28141. else {
  28142. throw "Depth renderer does not support int texture type";
  28143. }
  28144. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28145. }
  28146. return this._depthRenderer[camera.id];
  28147. };
  28148. /**
  28149. * Disables a depth renderer for a given camera
  28150. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28151. */
  28152. Scene.prototype.disableDepthRenderer = function (camera) {
  28153. camera = camera || this.activeCamera;
  28154. if (!camera || !this._depthRenderer[camera.id]) {
  28155. return;
  28156. }
  28157. this._depthRenderer[camera.id].dispose();
  28158. delete this._depthRenderer[camera.id];
  28159. };
  28160. /**
  28161. * Enables a GeometryBufferRender and associates it with the scene
  28162. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28163. * @returns the GeometryBufferRenderer
  28164. */
  28165. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28166. if (ratio === void 0) { ratio = 1; }
  28167. if (this._geometryBufferRenderer) {
  28168. return this._geometryBufferRenderer;
  28169. }
  28170. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28171. if (!this._geometryBufferRenderer.isSupported) {
  28172. this._geometryBufferRenderer = null;
  28173. }
  28174. return this._geometryBufferRenderer;
  28175. };
  28176. /**
  28177. * Disables the GeometryBufferRender associated with the scene
  28178. */
  28179. Scene.prototype.disableGeometryBufferRenderer = function () {
  28180. if (!this._geometryBufferRenderer) {
  28181. return;
  28182. }
  28183. this._geometryBufferRenderer.dispose();
  28184. this._geometryBufferRenderer = null;
  28185. };
  28186. /**
  28187. * Freeze all materials
  28188. * A frozen material will not be updatable but should be faster to render
  28189. */
  28190. Scene.prototype.freezeMaterials = function () {
  28191. for (var i = 0; i < this.materials.length; i++) {
  28192. this.materials[i].freeze();
  28193. }
  28194. };
  28195. /**
  28196. * Unfreeze all materials
  28197. * A frozen material will not be updatable but should be faster to render
  28198. */
  28199. Scene.prototype.unfreezeMaterials = function () {
  28200. for (var i = 0; i < this.materials.length; i++) {
  28201. this.materials[i].unfreeze();
  28202. }
  28203. };
  28204. /**
  28205. * Releases all held ressources
  28206. */
  28207. Scene.prototype.dispose = function () {
  28208. this.beforeRender = null;
  28209. this.afterRender = null;
  28210. this.skeletons = [];
  28211. this.morphTargetManagers = [];
  28212. this.importedMeshesFiles = new Array();
  28213. this.stopAllAnimations();
  28214. this.resetCachedMaterial();
  28215. for (var key in this._depthRenderer) {
  28216. this._depthRenderer[key].dispose();
  28217. }
  28218. if (this._gamepadManager) {
  28219. this._gamepadManager.dispose();
  28220. this._gamepadManager = null;
  28221. }
  28222. // Smart arrays
  28223. if (this.activeCamera) {
  28224. this.activeCamera._activeMeshes.dispose();
  28225. this.activeCamera = null;
  28226. }
  28227. this._activeMeshes.dispose();
  28228. this._renderingManager.dispose();
  28229. this._processedMaterials.dispose();
  28230. this._activeParticleSystems.dispose();
  28231. this._activeSkeletons.dispose();
  28232. this._softwareSkinnedMeshes.dispose();
  28233. this._renderTargets.dispose();
  28234. this._registeredForLateAnimationBindings.dispose();
  28235. if (this._boundingBoxRenderer) {
  28236. this._boundingBoxRenderer.dispose();
  28237. }
  28238. this._meshesForIntersections.dispose();
  28239. this._toBeDisposed.dispose();
  28240. // Abort active requests
  28241. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  28242. var request = _a[_i];
  28243. request.abort();
  28244. }
  28245. // Debug layer
  28246. if (this._debugLayer) {
  28247. this._debugLayer.hide();
  28248. }
  28249. // Events
  28250. this.onDisposeObservable.notifyObservers(this);
  28251. this.onDisposeObservable.clear();
  28252. this.onBeforeRenderObservable.clear();
  28253. this.onAfterRenderObservable.clear();
  28254. this.onBeforeRenderTargetsRenderObservable.clear();
  28255. this.onAfterRenderTargetsRenderObservable.clear();
  28256. this.onAfterStepObservable.clear();
  28257. this.onBeforeStepObservable.clear();
  28258. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28259. this.onAfterActiveMeshesEvaluationObservable.clear();
  28260. this.onBeforeParticlesRenderingObservable.clear();
  28261. this.onAfterParticlesRenderingObservable.clear();
  28262. this.onBeforeSpritesRenderingObservable.clear();
  28263. this.onAfterSpritesRenderingObservable.clear();
  28264. this.onBeforeDrawPhaseObservable.clear();
  28265. this.onAfterDrawPhaseObservable.clear();
  28266. this.onBeforePhysicsObservable.clear();
  28267. this.onAfterPhysicsObservable.clear();
  28268. this.onBeforeAnimationsObservable.clear();
  28269. this.onAfterAnimationsObservable.clear();
  28270. this.onDataLoadedObservable.clear();
  28271. this.detachControl();
  28272. // Release sounds & sounds tracks
  28273. if (BABYLON.AudioEngine) {
  28274. this.disposeSounds();
  28275. }
  28276. // VR Helper
  28277. if (this.VRHelper) {
  28278. this.VRHelper.dispose();
  28279. }
  28280. // Detach cameras
  28281. var canvas = this._engine.getRenderingCanvas();
  28282. if (canvas) {
  28283. var index;
  28284. for (index = 0; index < this.cameras.length; index++) {
  28285. this.cameras[index].detachControl(canvas);
  28286. }
  28287. }
  28288. // Release animation groups
  28289. while (this.animationGroups.length) {
  28290. this.animationGroups[0].dispose();
  28291. }
  28292. // Release lights
  28293. while (this.lights.length) {
  28294. this.lights[0].dispose();
  28295. }
  28296. // Release meshes
  28297. while (this.meshes.length) {
  28298. this.meshes[0].dispose(true);
  28299. }
  28300. while (this.transformNodes.length) {
  28301. this.removeTransformNode(this.transformNodes[0]);
  28302. }
  28303. // Release cameras
  28304. while (this.cameras.length) {
  28305. this.cameras[0].dispose();
  28306. }
  28307. // Release materials
  28308. if (this.defaultMaterial) {
  28309. this.defaultMaterial.dispose();
  28310. }
  28311. while (this.multiMaterials.length) {
  28312. this.multiMaterials[0].dispose();
  28313. }
  28314. while (this.materials.length) {
  28315. this.materials[0].dispose();
  28316. }
  28317. // Release particles
  28318. while (this.particleSystems.length) {
  28319. this.particleSystems[0].dispose();
  28320. }
  28321. // Release sprites
  28322. while (this.spriteManagers.length) {
  28323. this.spriteManagers[0].dispose();
  28324. }
  28325. // Release postProcesses
  28326. while (this.postProcesses.length) {
  28327. this.postProcesses[0].dispose();
  28328. }
  28329. // Release layers
  28330. while (this.layers.length) {
  28331. this.layers[0].dispose();
  28332. }
  28333. while (this.effectLayers.length) {
  28334. this.effectLayers[0].dispose();
  28335. }
  28336. // Release textures
  28337. while (this.textures.length) {
  28338. this.textures[0].dispose();
  28339. }
  28340. // Release UBO
  28341. this._sceneUbo.dispose();
  28342. if (this._alternateSceneUbo) {
  28343. this._alternateSceneUbo.dispose();
  28344. }
  28345. // Post-processes
  28346. this.postProcessManager.dispose();
  28347. if (this._postProcessRenderPipelineManager) {
  28348. this._postProcessRenderPipelineManager.dispose();
  28349. }
  28350. // Physics
  28351. if (this._physicsEngine) {
  28352. this.disablePhysicsEngine();
  28353. }
  28354. // Remove from engine
  28355. index = this._engine.scenes.indexOf(this);
  28356. if (index > -1) {
  28357. this._engine.scenes.splice(index, 1);
  28358. }
  28359. this._engine.wipeCaches(true);
  28360. this._isDisposed = true;
  28361. };
  28362. Object.defineProperty(Scene.prototype, "isDisposed", {
  28363. /**
  28364. * Gets if the scene is already disposed
  28365. */
  28366. get: function () {
  28367. return this._isDisposed;
  28368. },
  28369. enumerable: true,
  28370. configurable: true
  28371. });
  28372. /**
  28373. * Releases sounds & soundtracks
  28374. */
  28375. Scene.prototype.disposeSounds = function () {
  28376. if (!this._mainSoundTrack) {
  28377. return;
  28378. }
  28379. this.mainSoundTrack.dispose();
  28380. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28381. this.soundTracks[scIndex].dispose();
  28382. }
  28383. };
  28384. /**
  28385. * Call this function to reduce memory footprint of the scene.
  28386. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28387. */
  28388. Scene.prototype.clearCachedVertexData = function () {
  28389. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28390. var mesh = this.meshes[meshIndex];
  28391. var geometry = mesh.geometry;
  28392. if (geometry) {
  28393. geometry._indices = [];
  28394. for (var vbName in geometry._vertexBuffers) {
  28395. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28396. continue;
  28397. }
  28398. geometry._vertexBuffers[vbName]._buffer._data = null;
  28399. }
  28400. }
  28401. }
  28402. };
  28403. /**
  28404. * This function will remove the local cached buffer data from texture.
  28405. * It will save memory but will prevent the texture from being rebuilt
  28406. */
  28407. Scene.prototype.cleanCachedTextureBuffer = function () {
  28408. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28409. var baseTexture = _a[_i];
  28410. var buffer = baseTexture._buffer;
  28411. if (buffer) {
  28412. baseTexture._buffer = null;
  28413. }
  28414. }
  28415. };
  28416. // Octrees
  28417. /**
  28418. * Get the world extend vectors with an optional filter
  28419. *
  28420. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28421. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28422. */
  28423. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28424. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28425. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28426. filterPredicate = filterPredicate || (function () { return true; });
  28427. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28428. mesh.computeWorldMatrix(true);
  28429. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28430. return;
  28431. }
  28432. var boundingInfo = mesh.getBoundingInfo();
  28433. var minBox = boundingInfo.boundingBox.minimumWorld;
  28434. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28435. BABYLON.Tools.CheckExtends(minBox, min, max);
  28436. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28437. });
  28438. return {
  28439. min: min,
  28440. max: max
  28441. };
  28442. };
  28443. /**
  28444. * Creates or updates the octree used to boost selection (picking)
  28445. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28446. * @param maxCapacity defines the maximum capacity per leaf
  28447. * @param maxDepth defines the maximum depth of the octree
  28448. * @returns an octree of AbstractMesh
  28449. */
  28450. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28451. if (maxCapacity === void 0) { maxCapacity = 64; }
  28452. if (maxDepth === void 0) { maxDepth = 2; }
  28453. if (!this._selectionOctree) {
  28454. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28455. }
  28456. var worldExtends = this.getWorldExtends();
  28457. // Update octree
  28458. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28459. return this._selectionOctree;
  28460. };
  28461. // Picking
  28462. /**
  28463. * Creates a ray that can be used to pick in the scene
  28464. * @param x defines the x coordinate of the origin (on-screen)
  28465. * @param y defines the y coordinate of the origin (on-screen)
  28466. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28467. * @param camera defines the camera to use for the picking
  28468. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28469. * @returns a Ray
  28470. */
  28471. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28472. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28473. var result = BABYLON.Ray.Zero();
  28474. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28475. return result;
  28476. };
  28477. /**
  28478. * Creates a ray that can be used to pick in the scene
  28479. * @param x defines the x coordinate of the origin (on-screen)
  28480. * @param y defines the y coordinate of the origin (on-screen)
  28481. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28482. * @param result defines the ray where to store the picking ray
  28483. * @param camera defines the camera to use for the picking
  28484. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28485. * @returns the current scene
  28486. */
  28487. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28488. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28489. var engine = this._engine;
  28490. if (!camera) {
  28491. if (!this.activeCamera)
  28492. throw new Error("Active camera not set");
  28493. camera = this.activeCamera;
  28494. }
  28495. var cameraViewport = camera.viewport;
  28496. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28497. // Moving coordinates to local viewport world
  28498. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28499. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28500. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28501. return this;
  28502. };
  28503. /**
  28504. * Creates a ray that can be used to pick in the scene
  28505. * @param x defines the x coordinate of the origin (on-screen)
  28506. * @param y defines the y coordinate of the origin (on-screen)
  28507. * @param camera defines the camera to use for the picking
  28508. * @returns a Ray
  28509. */
  28510. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28511. var result = BABYLON.Ray.Zero();
  28512. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28513. return result;
  28514. };
  28515. /**
  28516. * Creates a ray that can be used to pick in the scene
  28517. * @param x defines the x coordinate of the origin (on-screen)
  28518. * @param y defines the y coordinate of the origin (on-screen)
  28519. * @param result defines the ray where to store the picking ray
  28520. * @param camera defines the camera to use for the picking
  28521. * @returns the current scene
  28522. */
  28523. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28524. if (!BABYLON.PickingInfo) {
  28525. return this;
  28526. }
  28527. var engine = this._engine;
  28528. if (!camera) {
  28529. if (!this.activeCamera)
  28530. throw new Error("Active camera not set");
  28531. camera = this.activeCamera;
  28532. }
  28533. var cameraViewport = camera.viewport;
  28534. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28535. var identity = BABYLON.Matrix.Identity();
  28536. // Moving coordinates to local viewport world
  28537. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28538. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28539. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28540. return this;
  28541. };
  28542. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28543. if (!BABYLON.PickingInfo) {
  28544. return null;
  28545. }
  28546. var pickingInfo = null;
  28547. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28548. var mesh = this.meshes[meshIndex];
  28549. if (predicate) {
  28550. if (!predicate(mesh)) {
  28551. continue;
  28552. }
  28553. }
  28554. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28555. continue;
  28556. }
  28557. var world = mesh.getWorldMatrix();
  28558. var ray = rayFunction(world);
  28559. var result = mesh.intersects(ray, fastCheck);
  28560. if (!result || !result.hit)
  28561. continue;
  28562. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28563. continue;
  28564. pickingInfo = result;
  28565. if (fastCheck) {
  28566. break;
  28567. }
  28568. }
  28569. return pickingInfo || new BABYLON.PickingInfo();
  28570. };
  28571. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28572. if (!BABYLON.PickingInfo) {
  28573. return null;
  28574. }
  28575. var pickingInfos = new Array();
  28576. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28577. var mesh = this.meshes[meshIndex];
  28578. if (predicate) {
  28579. if (!predicate(mesh)) {
  28580. continue;
  28581. }
  28582. }
  28583. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28584. continue;
  28585. }
  28586. var world = mesh.getWorldMatrix();
  28587. var ray = rayFunction(world);
  28588. var result = mesh.intersects(ray, false);
  28589. if (!result || !result.hit)
  28590. continue;
  28591. pickingInfos.push(result);
  28592. }
  28593. return pickingInfos;
  28594. };
  28595. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28596. if (!BABYLON.PickingInfo) {
  28597. return null;
  28598. }
  28599. var pickingInfo = null;
  28600. if (!camera) {
  28601. if (!this.activeCamera) {
  28602. return null;
  28603. }
  28604. camera = this.activeCamera;
  28605. }
  28606. if (this.spriteManagers.length > 0) {
  28607. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28608. var spriteManager = this.spriteManagers[spriteIndex];
  28609. if (!spriteManager.isPickable) {
  28610. continue;
  28611. }
  28612. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28613. if (!result || !result.hit)
  28614. continue;
  28615. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28616. continue;
  28617. pickingInfo = result;
  28618. if (fastCheck) {
  28619. break;
  28620. }
  28621. }
  28622. }
  28623. return pickingInfo || new BABYLON.PickingInfo();
  28624. };
  28625. /** Launch a ray to try to pick a mesh in the scene
  28626. * @param x position on screen
  28627. * @param y position on screen
  28628. * @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
  28629. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28630. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28631. * @returns a PickingInfo
  28632. */
  28633. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28634. var _this = this;
  28635. if (!BABYLON.PickingInfo) {
  28636. return null;
  28637. }
  28638. var result = this._internalPick(function (world) {
  28639. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28640. return _this._tempPickingRay;
  28641. }, predicate, fastCheck);
  28642. if (result) {
  28643. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28644. }
  28645. return result;
  28646. };
  28647. /** Launch a ray to try to pick a sprite in the scene
  28648. * @param x position on screen
  28649. * @param y position on screen
  28650. * @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
  28651. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28652. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28653. * @returns a PickingInfo
  28654. */
  28655. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28656. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28657. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28658. };
  28659. /** Use the given ray to pick a mesh in the scene
  28660. * @param ray The ray to use to pick meshes
  28661. * @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
  28662. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28663. * @returns a PickingInfo
  28664. */
  28665. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28666. var _this = this;
  28667. var result = this._internalPick(function (world) {
  28668. if (!_this._pickWithRayInverseMatrix) {
  28669. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28670. }
  28671. world.invertToRef(_this._pickWithRayInverseMatrix);
  28672. if (!_this._cachedRayForTransform) {
  28673. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28674. }
  28675. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28676. return _this._cachedRayForTransform;
  28677. }, predicate, fastCheck);
  28678. if (result) {
  28679. result.ray = ray;
  28680. }
  28681. return result;
  28682. };
  28683. /**
  28684. * Launch a ray to try to pick a mesh in the scene
  28685. * @param x X position on screen
  28686. * @param y Y position on screen
  28687. * @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
  28688. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28689. * @returns an array of PickingInfo
  28690. */
  28691. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28692. var _this = this;
  28693. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28694. };
  28695. /**
  28696. * Launch a ray to try to pick a mesh in the scene
  28697. * @param ray Ray to use
  28698. * @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
  28699. * @returns an array of PickingInfo
  28700. */
  28701. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28702. var _this = this;
  28703. return this._internalMultiPick(function (world) {
  28704. if (!_this._pickWithRayInverseMatrix) {
  28705. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28706. }
  28707. world.invertToRef(_this._pickWithRayInverseMatrix);
  28708. if (!_this._cachedRayForTransform) {
  28709. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28710. }
  28711. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28712. return _this._cachedRayForTransform;
  28713. }, predicate);
  28714. };
  28715. /**
  28716. * Force the value of meshUnderPointer
  28717. * @param mesh defines the mesh to use
  28718. */
  28719. Scene.prototype.setPointerOverMesh = function (mesh) {
  28720. if (this._pointerOverMesh === mesh) {
  28721. return;
  28722. }
  28723. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28724. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28725. }
  28726. this._pointerOverMesh = mesh;
  28727. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28728. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28729. }
  28730. };
  28731. /**
  28732. * Gets the mesh under the pointer
  28733. * @returns a Mesh or null if no mesh is under the pointer
  28734. */
  28735. Scene.prototype.getPointerOverMesh = function () {
  28736. return this._pointerOverMesh;
  28737. };
  28738. /**
  28739. * Force the sprite under the pointer
  28740. * @param sprite defines the sprite to use
  28741. */
  28742. Scene.prototype.setPointerOverSprite = function (sprite) {
  28743. if (this._pointerOverSprite === sprite) {
  28744. return;
  28745. }
  28746. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28747. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28748. }
  28749. this._pointerOverSprite = sprite;
  28750. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28751. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28752. }
  28753. };
  28754. /**
  28755. * Gets the sprite under the pointer
  28756. * @returns a Sprite or null if no sprite is under the pointer
  28757. */
  28758. Scene.prototype.getPointerOverSprite = function () {
  28759. return this._pointerOverSprite;
  28760. };
  28761. // Physics
  28762. /**
  28763. * Gets the current physics engine
  28764. * @returns a PhysicsEngine or null if none attached
  28765. */
  28766. Scene.prototype.getPhysicsEngine = function () {
  28767. return this._physicsEngine;
  28768. };
  28769. /**
  28770. * Enables physics to the current scene
  28771. * @param gravity defines the scene's gravity for the physics engine
  28772. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28773. * @return a boolean indicating if the physics engine was initialized
  28774. */
  28775. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28776. if (gravity === void 0) { gravity = null; }
  28777. if (this._physicsEngine) {
  28778. return true;
  28779. }
  28780. try {
  28781. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28782. return true;
  28783. }
  28784. catch (e) {
  28785. BABYLON.Tools.Error(e.message);
  28786. return false;
  28787. }
  28788. };
  28789. /**
  28790. * Disables and disposes the physics engine associated with the scene
  28791. */
  28792. Scene.prototype.disablePhysicsEngine = function () {
  28793. if (!this._physicsEngine) {
  28794. return;
  28795. }
  28796. this._physicsEngine.dispose();
  28797. this._physicsEngine = null;
  28798. };
  28799. /**
  28800. * Gets a boolean indicating if there is an active physics engine
  28801. * @returns a boolean indicating if there is an active physics engine
  28802. */
  28803. Scene.prototype.isPhysicsEnabled = function () {
  28804. return this._physicsEngine !== undefined;
  28805. };
  28806. /**
  28807. * Deletes a physics compound impostor
  28808. * @param compound defines the compound to delete
  28809. */
  28810. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28811. var mesh = compound.parts[0].mesh;
  28812. if (mesh.physicsImpostor) {
  28813. mesh.physicsImpostor.dispose( /*true*/);
  28814. mesh.physicsImpostor = null;
  28815. }
  28816. };
  28817. // Misc.
  28818. /** @hidden */
  28819. Scene.prototype._rebuildGeometries = function () {
  28820. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28821. var geometry = _a[_i];
  28822. geometry._rebuild();
  28823. }
  28824. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28825. var mesh = _c[_b];
  28826. mesh._rebuild();
  28827. }
  28828. if (this.postProcessManager) {
  28829. this.postProcessManager._rebuild();
  28830. }
  28831. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28832. var layer = _e[_d];
  28833. layer._rebuild();
  28834. }
  28835. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28836. var effectLayer = _g[_f];
  28837. effectLayer._rebuild();
  28838. }
  28839. if (this._boundingBoxRenderer) {
  28840. this._boundingBoxRenderer._rebuild();
  28841. }
  28842. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28843. var system = _j[_h];
  28844. system.rebuild();
  28845. }
  28846. if (this._postProcessRenderPipelineManager) {
  28847. this._postProcessRenderPipelineManager._rebuild();
  28848. }
  28849. };
  28850. /** @hidden */
  28851. Scene.prototype._rebuildTextures = function () {
  28852. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28853. var texture = _a[_i];
  28854. texture._rebuild();
  28855. }
  28856. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28857. };
  28858. /**
  28859. * Creates a default light for the scene.
  28860. * @param replace Whether to replace the existing lights in the scene.
  28861. */
  28862. Scene.prototype.createDefaultLight = function (replace) {
  28863. if (replace === void 0) { replace = false; }
  28864. // Dispose existing light in replace mode.
  28865. if (replace) {
  28866. if (this.lights) {
  28867. for (var i = 0; i < this.lights.length; i++) {
  28868. this.lights[i].dispose();
  28869. }
  28870. }
  28871. }
  28872. // Light
  28873. if (this.lights.length === 0) {
  28874. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28875. }
  28876. };
  28877. /**
  28878. * Creates a default camera for the scene.
  28879. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28880. * @param replace Whether to replace the existing active camera in the scene.
  28881. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28882. */
  28883. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28884. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28885. if (replace === void 0) { replace = false; }
  28886. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28887. // Dispose existing camera in replace mode.
  28888. if (replace) {
  28889. if (this.activeCamera) {
  28890. this.activeCamera.dispose();
  28891. this.activeCamera = null;
  28892. }
  28893. }
  28894. // Camera
  28895. if (!this.activeCamera) {
  28896. var worldExtends = this.getWorldExtends();
  28897. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28898. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28899. var camera;
  28900. var radius = worldSize.length() * 1.5;
  28901. // empty scene scenario!
  28902. if (!isFinite(radius)) {
  28903. radius = 1;
  28904. worldCenter.copyFromFloats(0, 0, 0);
  28905. }
  28906. if (createArcRotateCamera) {
  28907. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28908. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28909. arcRotateCamera.wheelPrecision = 100 / radius;
  28910. camera = arcRotateCamera;
  28911. }
  28912. else {
  28913. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28914. freeCamera.setTarget(worldCenter);
  28915. camera = freeCamera;
  28916. }
  28917. camera.minZ = radius * 0.01;
  28918. camera.maxZ = radius * 1000;
  28919. camera.speed = radius * 0.2;
  28920. this.activeCamera = camera;
  28921. var canvas = this.getEngine().getRenderingCanvas();
  28922. if (attachCameraControls && canvas) {
  28923. camera.attachControl(canvas);
  28924. }
  28925. }
  28926. };
  28927. /**
  28928. * Creates a default camera and a default light
  28929. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28930. * @param replace defines if the camera and/or light will replace the existing ones
  28931. * @param attachCameraControls defines if attachControl will be called on the new camera
  28932. */
  28933. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28934. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28935. if (replace === void 0) { replace = false; }
  28936. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28937. this.createDefaultLight(replace);
  28938. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28939. };
  28940. /**
  28941. * Creates a new sky box
  28942. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28943. * @param environmentTexture defines the texture to use as environment texture
  28944. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28945. * @param scale defines the overall scale of the skybox
  28946. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28947. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28948. * @returns a new mesh holding the sky box
  28949. */
  28950. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28951. if (pbr === void 0) { pbr = false; }
  28952. if (scale === void 0) { scale = 1000; }
  28953. if (blur === void 0) { blur = 0; }
  28954. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28955. if (!environmentTexture) {
  28956. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28957. return null;
  28958. }
  28959. if (setGlobalEnvTexture) {
  28960. if (environmentTexture) {
  28961. this.environmentTexture = environmentTexture;
  28962. }
  28963. }
  28964. // Skybox
  28965. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28966. if (pbr) {
  28967. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28968. hdrSkyboxMaterial.backFaceCulling = false;
  28969. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28970. if (hdrSkyboxMaterial.reflectionTexture) {
  28971. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28972. }
  28973. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28974. hdrSkyboxMaterial.disableLighting = true;
  28975. hdrSkyboxMaterial.twoSidedLighting = true;
  28976. hdrSkybox.infiniteDistance = true;
  28977. hdrSkybox.material = hdrSkyboxMaterial;
  28978. }
  28979. else {
  28980. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28981. skyboxMaterial.backFaceCulling = false;
  28982. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28983. if (skyboxMaterial.reflectionTexture) {
  28984. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28985. }
  28986. skyboxMaterial.disableLighting = true;
  28987. hdrSkybox.infiniteDistance = true;
  28988. hdrSkybox.material = skyboxMaterial;
  28989. }
  28990. return hdrSkybox;
  28991. };
  28992. /**
  28993. * Creates a new environment
  28994. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28995. * @param options defines the options you can use to configure the environment
  28996. * @returns the new EnvironmentHelper
  28997. */
  28998. Scene.prototype.createDefaultEnvironment = function (options) {
  28999. if (BABYLON.EnvironmentHelper) {
  29000. return new BABYLON.EnvironmentHelper(options, this);
  29001. }
  29002. return null;
  29003. };
  29004. /**
  29005. * Creates a new VREXperienceHelper
  29006. * @see http://doc.babylonjs.com/how_to/webvr_helper
  29007. * @param webVROptions defines the options used to create the new VREXperienceHelper
  29008. * @returns a new VREXperienceHelper
  29009. */
  29010. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  29011. if (webVROptions === void 0) { webVROptions = {}; }
  29012. return new BABYLON.VRExperienceHelper(this, webVROptions);
  29013. };
  29014. // Tags
  29015. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29016. if (tagsQuery === undefined) {
  29017. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29018. return list;
  29019. }
  29020. var listByTags = [];
  29021. forEach = forEach || (function (item) { return; });
  29022. for (var i in list) {
  29023. var item = list[i];
  29024. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29025. listByTags.push(item);
  29026. forEach(item);
  29027. }
  29028. }
  29029. return listByTags;
  29030. };
  29031. /**
  29032. * Get a list of meshes by tags
  29033. * @param tagsQuery defines the tags query to use
  29034. * @param forEach defines a predicate used to filter results
  29035. * @returns an array of Mesh
  29036. */
  29037. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29038. return this._getByTags(this.meshes, tagsQuery, forEach);
  29039. };
  29040. /**
  29041. * Get a list of cameras by tags
  29042. * @param tagsQuery defines the tags query to use
  29043. * @param forEach defines a predicate used to filter results
  29044. * @returns an array of Camera
  29045. */
  29046. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29047. return this._getByTags(this.cameras, tagsQuery, forEach);
  29048. };
  29049. /**
  29050. * Get a list of lights by tags
  29051. * @param tagsQuery defines the tags query to use
  29052. * @param forEach defines a predicate used to filter results
  29053. * @returns an array of Light
  29054. */
  29055. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29056. return this._getByTags(this.lights, tagsQuery, forEach);
  29057. };
  29058. /**
  29059. * Get a list of materials by tags
  29060. * @param tagsQuery defines the tags query to use
  29061. * @param forEach defines a predicate used to filter results
  29062. * @returns an array of Material
  29063. */
  29064. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29065. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29066. };
  29067. /**
  29068. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29069. * This allowed control for front to back rendering or reversly depending of the special needs.
  29070. *
  29071. * @param renderingGroupId The rendering group id corresponding to its index
  29072. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29073. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29074. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29075. */
  29076. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29077. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29078. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29079. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29080. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29081. };
  29082. /**
  29083. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29084. *
  29085. * @param renderingGroupId The rendering group id corresponding to its index
  29086. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29087. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29088. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29089. */
  29090. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29091. if (depth === void 0) { depth = true; }
  29092. if (stencil === void 0) { stencil = true; }
  29093. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29094. };
  29095. /**
  29096. * Will flag all materials as dirty to trigger new shader compilation
  29097. * @param flag defines the flag used to specify which material part must be marked as dirty
  29098. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29099. */
  29100. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29101. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29102. var material = _a[_i];
  29103. if (predicate && !predicate(material)) {
  29104. continue;
  29105. }
  29106. material.markAsDirty(flag);
  29107. }
  29108. };
  29109. /** @hidden */
  29110. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29111. var _this = this;
  29112. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29113. this._activeRequests.push(request);
  29114. request.onCompleteObservable.add(function (request) {
  29115. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29116. });
  29117. return request;
  29118. };
  29119. /** @hidden */
  29120. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29121. var _this = this;
  29122. return new Promise(function (resolve, reject) {
  29123. _this._loadFile(url, function (data) {
  29124. resolve(data);
  29125. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29126. reject(exception);
  29127. });
  29128. });
  29129. };
  29130. // Statics
  29131. Scene._FOGMODE_NONE = 0;
  29132. Scene._FOGMODE_EXP = 1;
  29133. Scene._FOGMODE_EXP2 = 2;
  29134. Scene._FOGMODE_LINEAR = 3;
  29135. Scene._uniqueIdCounter = 0;
  29136. /**
  29137. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29138. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29139. */
  29140. Scene.MinDeltaTime = 1.0;
  29141. /**
  29142. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29143. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29144. */
  29145. Scene.MaxDeltaTime = 1000.0;
  29146. /** The distance in pixel that you have to move to prevent some events */
  29147. Scene.DragMovementThreshold = 10; // in pixels
  29148. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29149. Scene.LongPressDelay = 500; // in milliseconds
  29150. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29151. Scene.DoubleClickDelay = 300; // in milliseconds
  29152. /** If you need to check double click without raising a single click at first click, enable this flag */
  29153. Scene.ExclusiveDoubleClickMode = false;
  29154. return Scene;
  29155. }());
  29156. BABYLON.Scene = Scene;
  29157. })(BABYLON || (BABYLON = {}));
  29158. //# sourceMappingURL=babylon.scene.js.map
  29159. var BABYLON;
  29160. (function (BABYLON) {
  29161. /**
  29162. * Set of assets to keep when moving a scene into an asset container.
  29163. */
  29164. var KeepAssets = /** @class */ (function () {
  29165. function KeepAssets() {
  29166. /**
  29167. * Cameras to keep.
  29168. */
  29169. this.cameras = new Array();
  29170. /**
  29171. * Lights to keep.
  29172. */
  29173. this.lights = new Array();
  29174. /**
  29175. * Meshes to keep.
  29176. */
  29177. this.meshes = new Array();
  29178. /**
  29179. * Skeletons to keep.
  29180. */
  29181. this.skeletons = new Array();
  29182. /**
  29183. * ParticleSystems to keep.
  29184. */
  29185. this.particleSystems = new Array();
  29186. /**
  29187. * Animations to keep.
  29188. */
  29189. this.animations = new Array();
  29190. /**
  29191. * AnimationGroups to keep.
  29192. */
  29193. this.animationGroups = new Array();
  29194. /**
  29195. * MultiMaterials to keep.
  29196. */
  29197. this.multiMaterials = new Array();
  29198. /**
  29199. * Materials to keep.
  29200. */
  29201. this.materials = new Array();
  29202. /**
  29203. * MorphTargetManagers to keep.
  29204. */
  29205. this.morphTargetManagers = new Array();
  29206. /**
  29207. * Geometries to keep.
  29208. */
  29209. this.geometries = new Array();
  29210. /**
  29211. * TransformNodes to keep.
  29212. */
  29213. this.transformNodes = new Array();
  29214. /**
  29215. * LensFlareSystems to keep.
  29216. */
  29217. this.lensFlareSystems = new Array();
  29218. /**
  29219. * ShadowGenerators to keep.
  29220. */
  29221. this.shadowGenerators = new Array();
  29222. /**
  29223. * ActionManagers to keep.
  29224. */
  29225. this.actionManagers = new Array();
  29226. /**
  29227. * Sounds to keep.
  29228. */
  29229. this.sounds = new Array();
  29230. /**
  29231. * Textures to keep.
  29232. */
  29233. this.textures = new Array();
  29234. /**
  29235. * Effect layers to keep.
  29236. */
  29237. this.effectLayers = new Array();
  29238. }
  29239. return KeepAssets;
  29240. }());
  29241. BABYLON.KeepAssets = KeepAssets;
  29242. /**
  29243. * Container with a set of assets that can be added or removed from a scene.
  29244. */
  29245. var AssetContainer = /** @class */ (function () {
  29246. /**
  29247. * Instantiates an AssetContainer.
  29248. * @param scene The scene the AssetContainer belongs to.
  29249. */
  29250. function AssetContainer(scene) {
  29251. // Objects
  29252. /**
  29253. * Cameras populated in the container.
  29254. */
  29255. this.cameras = new Array();
  29256. /**
  29257. * Lights populated in the container.
  29258. */
  29259. this.lights = new Array();
  29260. /**
  29261. * Meshes populated in the container.
  29262. */
  29263. this.meshes = new Array();
  29264. /**
  29265. * Skeletons populated in the container.
  29266. */
  29267. this.skeletons = new Array();
  29268. /**
  29269. * ParticleSystems populated in the container.
  29270. */
  29271. this.particleSystems = new Array();
  29272. /**
  29273. * Animations populated in the container.
  29274. */
  29275. this.animations = new Array();
  29276. /**
  29277. * AnimationGroups populated in the container.
  29278. */
  29279. this.animationGroups = new Array();
  29280. /**
  29281. * MultiMaterials populated in the container.
  29282. */
  29283. this.multiMaterials = new Array();
  29284. /**
  29285. * Materials populated in the container.
  29286. */
  29287. this.materials = new Array();
  29288. /**
  29289. * MorphTargetManagers populated in the container.
  29290. */
  29291. this.morphTargetManagers = new Array();
  29292. /**
  29293. * Geometries populated in the container.
  29294. */
  29295. this.geometries = new Array();
  29296. /**
  29297. * TransformNodes populated in the container.
  29298. */
  29299. this.transformNodes = new Array();
  29300. /**
  29301. * LensFlareSystems populated in the container.
  29302. */
  29303. this.lensFlareSystems = new Array();
  29304. /**
  29305. * ShadowGenerators populated in the container.
  29306. */
  29307. this.shadowGenerators = new Array();
  29308. /**
  29309. * ActionManagers populated in the container.
  29310. */
  29311. this.actionManagers = new Array();
  29312. /**
  29313. * Sounds populated in the container.
  29314. */
  29315. this.sounds = new Array();
  29316. /**
  29317. * Textures populated in the container.
  29318. */
  29319. this.textures = new Array();
  29320. /**
  29321. * Effect layers populated in the container.
  29322. */
  29323. this.effectLayers = new Array();
  29324. this.scene = scene;
  29325. }
  29326. /**
  29327. * Adds all the assets from the container to the scene.
  29328. */
  29329. AssetContainer.prototype.addAllToScene = function () {
  29330. var _this = this;
  29331. this.cameras.forEach(function (o) {
  29332. _this.scene.addCamera(o);
  29333. });
  29334. this.lights.forEach(function (o) {
  29335. _this.scene.addLight(o);
  29336. });
  29337. this.meshes.forEach(function (o) {
  29338. _this.scene.addMesh(o);
  29339. });
  29340. this.skeletons.forEach(function (o) {
  29341. _this.scene.addSkeleton(o);
  29342. });
  29343. this.particleSystems.forEach(function (o) {
  29344. _this.scene.addParticleSystem(o);
  29345. });
  29346. this.animations.forEach(function (o) {
  29347. _this.scene.addAnimation(o);
  29348. });
  29349. this.animationGroups.forEach(function (o) {
  29350. _this.scene.addAnimationGroup(o);
  29351. });
  29352. this.multiMaterials.forEach(function (o) {
  29353. _this.scene.addMultiMaterial(o);
  29354. });
  29355. this.materials.forEach(function (o) {
  29356. _this.scene.addMaterial(o);
  29357. });
  29358. this.morphTargetManagers.forEach(function (o) {
  29359. _this.scene.addMorphTargetManager(o);
  29360. });
  29361. this.geometries.forEach(function (o) {
  29362. _this.scene.addGeometry(o);
  29363. });
  29364. this.transformNodes.forEach(function (o) {
  29365. _this.scene.addTransformNode(o);
  29366. });
  29367. this.lensFlareSystems.forEach(function (o) {
  29368. _this.scene.addLensFlareSystem(o);
  29369. });
  29370. this.actionManagers.forEach(function (o) {
  29371. _this.scene.addActionManager(o);
  29372. });
  29373. this.sounds.forEach(function (o) {
  29374. o.play();
  29375. o.autoplay = true;
  29376. _this.scene.mainSoundTrack.AddSound(o);
  29377. });
  29378. this.textures.forEach(function (o) {
  29379. _this.scene.addTexture(o);
  29380. });
  29381. this.effectLayers.forEach(function (o) {
  29382. _this.scene.addEffectLayer(o);
  29383. });
  29384. };
  29385. /**
  29386. * Removes all the assets in the container from the scene
  29387. */
  29388. AssetContainer.prototype.removeAllFromScene = function () {
  29389. var _this = this;
  29390. this.cameras.forEach(function (o) {
  29391. _this.scene.removeCamera(o);
  29392. });
  29393. this.lights.forEach(function (o) {
  29394. _this.scene.removeLight(o);
  29395. });
  29396. this.meshes.forEach(function (o) {
  29397. _this.scene.removeMesh(o);
  29398. });
  29399. this.skeletons.forEach(function (o) {
  29400. _this.scene.removeSkeleton(o);
  29401. });
  29402. this.particleSystems.forEach(function (o) {
  29403. _this.scene.removeParticleSystem(o);
  29404. });
  29405. this.animations.forEach(function (o) {
  29406. _this.scene.removeAnimation(o);
  29407. });
  29408. this.animationGroups.forEach(function (o) {
  29409. _this.scene.removeAnimationGroup(o);
  29410. });
  29411. this.multiMaterials.forEach(function (o) {
  29412. _this.scene.removeMultiMaterial(o);
  29413. });
  29414. this.materials.forEach(function (o) {
  29415. _this.scene.removeMaterial(o);
  29416. });
  29417. this.morphTargetManagers.forEach(function (o) {
  29418. _this.scene.removeMorphTargetManager(o);
  29419. });
  29420. this.geometries.forEach(function (o) {
  29421. _this.scene.removeGeometry(o);
  29422. });
  29423. this.transformNodes.forEach(function (o) {
  29424. _this.scene.removeTransformNode(o);
  29425. });
  29426. this.lensFlareSystems.forEach(function (o) {
  29427. _this.scene.removeLensFlareSystem(o);
  29428. });
  29429. this.actionManagers.forEach(function (o) {
  29430. _this.scene.removeActionManager(o);
  29431. });
  29432. this.sounds.forEach(function (o) {
  29433. o.stop();
  29434. o.autoplay = false;
  29435. _this.scene.mainSoundTrack.RemoveSound(o);
  29436. });
  29437. this.textures.forEach(function (o) {
  29438. _this.scene.removeTexture(o);
  29439. });
  29440. this.effectLayers.forEach(function (o) {
  29441. _this.scene.removeEffectLayer(o);
  29442. });
  29443. };
  29444. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29445. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29446. var asset = sourceAssets_1[_i];
  29447. var move = true;
  29448. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29449. var keepAsset = keepAssets_1[_a];
  29450. if (asset === keepAsset) {
  29451. move = false;
  29452. break;
  29453. }
  29454. }
  29455. if (move) {
  29456. targetAssets.push(asset);
  29457. }
  29458. }
  29459. };
  29460. /**
  29461. * Removes all the assets contained in the scene and adds them to the container.
  29462. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29463. */
  29464. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29465. if (keepAssets === undefined) {
  29466. keepAssets = new KeepAssets();
  29467. }
  29468. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29469. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29470. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29471. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29472. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29473. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29474. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29475. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29476. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29477. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29478. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29479. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29480. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29481. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29482. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29483. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29484. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29485. this.removeAllFromScene();
  29486. };
  29487. /**
  29488. * 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.
  29489. * @returns the root mesh
  29490. */
  29491. AssetContainer.prototype.createRootMesh = function () {
  29492. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29493. this.meshes.forEach(function (m) {
  29494. if (!m.parent) {
  29495. rootMesh.addChild(m);
  29496. }
  29497. });
  29498. this.meshes.unshift(rootMesh);
  29499. return rootMesh;
  29500. };
  29501. return AssetContainer;
  29502. }());
  29503. BABYLON.AssetContainer = AssetContainer;
  29504. })(BABYLON || (BABYLON = {}));
  29505. //# sourceMappingURL=babylon.assetContainer.js.map
  29506. var BABYLON;
  29507. (function (BABYLON) {
  29508. var Buffer = /** @class */ (function () {
  29509. /**
  29510. * Constructor
  29511. * @param engine the engine
  29512. * @param data the data to use for this buffer
  29513. * @param updatable whether the data is updatable
  29514. * @param stride the stride (optional)
  29515. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29516. * @param instanced whether the buffer is instanced (optional)
  29517. * @param useBytes set to true if the stride in in bytes (optional)
  29518. */
  29519. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29520. if (stride === void 0) { stride = 0; }
  29521. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29522. if (instanced === void 0) { instanced = false; }
  29523. if (useBytes === void 0) { useBytes = false; }
  29524. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29525. this._engine = engine.getScene().getEngine();
  29526. }
  29527. else {
  29528. this._engine = engine;
  29529. }
  29530. this._updatable = updatable;
  29531. this._instanced = instanced;
  29532. this._data = data;
  29533. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29534. if (!postponeInternalCreation) { // by default
  29535. this.create();
  29536. }
  29537. }
  29538. /**
  29539. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29540. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29541. * @param offset defines offset in the buffer (0 by default)
  29542. * @param size defines the size in floats of attributes (position is 3 for instance)
  29543. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29544. * @param instanced defines if the vertex buffer contains indexed data
  29545. * @param useBytes defines if the offset and stride are in bytes
  29546. * @returns the new vertex buffer
  29547. */
  29548. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29549. if (useBytes === void 0) { useBytes = false; }
  29550. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29551. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29552. // a lot of these parameters are ignored as they are overriden by the buffer
  29553. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29554. };
  29555. // Properties
  29556. Buffer.prototype.isUpdatable = function () {
  29557. return this._updatable;
  29558. };
  29559. Buffer.prototype.getData = function () {
  29560. return this._data;
  29561. };
  29562. Buffer.prototype.getBuffer = function () {
  29563. return this._buffer;
  29564. };
  29565. /**
  29566. * Gets the stride in float32 units (i.e. byte stride / 4).
  29567. * May not be an integer if the byte stride is not divisible by 4.
  29568. * DEPRECATED. Use byteStride instead.
  29569. * @returns the stride in float32 units
  29570. */
  29571. Buffer.prototype.getStrideSize = function () {
  29572. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29573. };
  29574. // Methods
  29575. Buffer.prototype.create = function (data) {
  29576. if (data === void 0) { data = null; }
  29577. if (!data && this._buffer) {
  29578. return; // nothing to do
  29579. }
  29580. data = data || this._data;
  29581. if (!data) {
  29582. return;
  29583. }
  29584. if (!this._buffer) { // create buffer
  29585. if (this._updatable) {
  29586. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29587. this._data = data;
  29588. }
  29589. else {
  29590. this._buffer = this._engine.createVertexBuffer(data);
  29591. }
  29592. }
  29593. else if (this._updatable) { // update buffer
  29594. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29595. this._data = data;
  29596. }
  29597. };
  29598. Buffer.prototype._rebuild = function () {
  29599. this._buffer = null;
  29600. this.create(this._data);
  29601. };
  29602. Buffer.prototype.update = function (data) {
  29603. this.create(data);
  29604. };
  29605. /**
  29606. * Updates the data directly.
  29607. * @param data the new data
  29608. * @param offset the new offset
  29609. * @param vertexCount the vertex count (optional)
  29610. * @param useBytes set to true if the offset is in bytes
  29611. */
  29612. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29613. if (useBytes === void 0) { useBytes = false; }
  29614. if (!this._buffer) {
  29615. return;
  29616. }
  29617. if (this._updatable) { // update buffer
  29618. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29619. this._data = null;
  29620. }
  29621. };
  29622. Buffer.prototype.dispose = function () {
  29623. if (!this._buffer) {
  29624. return;
  29625. }
  29626. if (this._engine._releaseBuffer(this._buffer)) {
  29627. this._buffer = null;
  29628. }
  29629. };
  29630. return Buffer;
  29631. }());
  29632. BABYLON.Buffer = Buffer;
  29633. })(BABYLON || (BABYLON = {}));
  29634. //# sourceMappingURL=babylon.buffer.js.map
  29635. var BABYLON;
  29636. (function (BABYLON) {
  29637. var VertexBuffer = /** @class */ (function () {
  29638. /**
  29639. * Constructor
  29640. * @param engine the engine
  29641. * @param data the data to use for this vertex buffer
  29642. * @param kind the vertex buffer kind
  29643. * @param updatable whether the data is updatable
  29644. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29645. * @param stride the stride (optional)
  29646. * @param instanced whether the buffer is instanced (optional)
  29647. * @param offset the offset of the data (optional)
  29648. * @param size the number of components (optional)
  29649. * @param type the type of the component (optional)
  29650. * @param normalized whether the data contains normalized data (optional)
  29651. * @param useBytes set to true if stride and offset are in bytes (optional)
  29652. */
  29653. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29654. if (normalized === void 0) { normalized = false; }
  29655. if (useBytes === void 0) { useBytes = false; }
  29656. if (data instanceof BABYLON.Buffer) {
  29657. this._buffer = data;
  29658. this._ownsBuffer = false;
  29659. }
  29660. else {
  29661. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29662. this._ownsBuffer = true;
  29663. }
  29664. this._kind = kind;
  29665. if (type == undefined) {
  29666. var data_1 = this.getData();
  29667. this.type = VertexBuffer.FLOAT;
  29668. if (data_1 instanceof Int8Array)
  29669. this.type = VertexBuffer.BYTE;
  29670. else if (data_1 instanceof Uint8Array)
  29671. this.type = VertexBuffer.UNSIGNED_BYTE;
  29672. else if (data_1 instanceof Int16Array)
  29673. this.type = VertexBuffer.SHORT;
  29674. else if (data_1 instanceof Uint16Array)
  29675. this.type = VertexBuffer.UNSIGNED_SHORT;
  29676. else if (data_1 instanceof Int32Array)
  29677. this.type = VertexBuffer.INT;
  29678. else if (data_1 instanceof Uint32Array)
  29679. this.type = VertexBuffer.UNSIGNED_INT;
  29680. }
  29681. else {
  29682. this.type = type;
  29683. }
  29684. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29685. if (useBytes) {
  29686. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29687. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29688. this.byteOffset = offset || 0;
  29689. }
  29690. else {
  29691. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29692. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29693. this.byteOffset = (offset || 0) * typeByteLength;
  29694. }
  29695. this.normalized = normalized;
  29696. this._instanced = instanced !== undefined ? instanced : false;
  29697. this._instanceDivisor = instanced ? 1 : 0;
  29698. }
  29699. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29700. /**
  29701. * Gets or sets the instance divisor when in instanced mode
  29702. */
  29703. get: function () {
  29704. return this._instanceDivisor;
  29705. },
  29706. set: function (value) {
  29707. this._instanceDivisor = value;
  29708. if (value == 0) {
  29709. this._instanced = false;
  29710. }
  29711. else {
  29712. this._instanced = true;
  29713. }
  29714. },
  29715. enumerable: true,
  29716. configurable: true
  29717. });
  29718. VertexBuffer.prototype._rebuild = function () {
  29719. if (!this._buffer) {
  29720. return;
  29721. }
  29722. this._buffer._rebuild();
  29723. };
  29724. /**
  29725. * Returns the kind of the VertexBuffer (string).
  29726. */
  29727. VertexBuffer.prototype.getKind = function () {
  29728. return this._kind;
  29729. };
  29730. // Properties
  29731. /**
  29732. * Boolean : is the VertexBuffer updatable ?
  29733. */
  29734. VertexBuffer.prototype.isUpdatable = function () {
  29735. return this._buffer.isUpdatable();
  29736. };
  29737. /**
  29738. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29739. */
  29740. VertexBuffer.prototype.getData = function () {
  29741. return this._buffer.getData();
  29742. };
  29743. /**
  29744. * Returns the WebGLBuffer associated to the VertexBuffer.
  29745. */
  29746. VertexBuffer.prototype.getBuffer = function () {
  29747. return this._buffer.getBuffer();
  29748. };
  29749. /**
  29750. * Returns the stride as a multiple of the type byte length.
  29751. * DEPRECATED. Use byteStride instead.
  29752. */
  29753. VertexBuffer.prototype.getStrideSize = function () {
  29754. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29755. };
  29756. /**
  29757. * Returns the offset as a multiple of the type byte length.
  29758. * DEPRECATED. Use byteOffset instead.
  29759. */
  29760. VertexBuffer.prototype.getOffset = function () {
  29761. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29762. };
  29763. /**
  29764. * Returns the number of components per vertex attribute (integer).
  29765. */
  29766. VertexBuffer.prototype.getSize = function () {
  29767. return this._size;
  29768. };
  29769. /**
  29770. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29771. */
  29772. VertexBuffer.prototype.getIsInstanced = function () {
  29773. return this._instanced;
  29774. };
  29775. /**
  29776. * Returns the instancing divisor, zero for non-instanced (integer).
  29777. */
  29778. VertexBuffer.prototype.getInstanceDivisor = function () {
  29779. return this._instanceDivisor;
  29780. };
  29781. // Methods
  29782. /**
  29783. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29784. * Returns the created WebGLBuffer.
  29785. */
  29786. VertexBuffer.prototype.create = function (data) {
  29787. return this._buffer.create(data);
  29788. };
  29789. /**
  29790. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29791. * This function will create a new buffer if the current one is not updatable
  29792. * Returns the updated WebGLBuffer.
  29793. */
  29794. VertexBuffer.prototype.update = function (data) {
  29795. return this._buffer.update(data);
  29796. };
  29797. /**
  29798. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29799. * Returns the directly updated WebGLBuffer.
  29800. * @param data the new data
  29801. * @param offset the new offset
  29802. * @param useBytes set to true if the offset is in bytes
  29803. */
  29804. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29805. if (useBytes === void 0) { useBytes = false; }
  29806. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29807. };
  29808. /**
  29809. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29810. */
  29811. VertexBuffer.prototype.dispose = function () {
  29812. if (this._ownsBuffer) {
  29813. this._buffer.dispose();
  29814. }
  29815. };
  29816. /**
  29817. * Enumerates each value of this vertex buffer as numbers.
  29818. * @param count the number of values to enumerate
  29819. * @param callback the callback function called for each value
  29820. */
  29821. VertexBuffer.prototype.forEach = function (count, callback) {
  29822. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29823. };
  29824. Object.defineProperty(VertexBuffer, "PositionKind", {
  29825. get: function () {
  29826. return VertexBuffer._PositionKind;
  29827. },
  29828. enumerable: true,
  29829. configurable: true
  29830. });
  29831. Object.defineProperty(VertexBuffer, "NormalKind", {
  29832. get: function () {
  29833. return VertexBuffer._NormalKind;
  29834. },
  29835. enumerable: true,
  29836. configurable: true
  29837. });
  29838. Object.defineProperty(VertexBuffer, "TangentKind", {
  29839. get: function () {
  29840. return VertexBuffer._TangentKind;
  29841. },
  29842. enumerable: true,
  29843. configurable: true
  29844. });
  29845. Object.defineProperty(VertexBuffer, "UVKind", {
  29846. get: function () {
  29847. return VertexBuffer._UVKind;
  29848. },
  29849. enumerable: true,
  29850. configurable: true
  29851. });
  29852. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29853. get: function () {
  29854. return VertexBuffer._UV2Kind;
  29855. },
  29856. enumerable: true,
  29857. configurable: true
  29858. });
  29859. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29860. get: function () {
  29861. return VertexBuffer._UV3Kind;
  29862. },
  29863. enumerable: true,
  29864. configurable: true
  29865. });
  29866. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29867. get: function () {
  29868. return VertexBuffer._UV4Kind;
  29869. },
  29870. enumerable: true,
  29871. configurable: true
  29872. });
  29873. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29874. get: function () {
  29875. return VertexBuffer._UV5Kind;
  29876. },
  29877. enumerable: true,
  29878. configurable: true
  29879. });
  29880. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29881. get: function () {
  29882. return VertexBuffer._UV6Kind;
  29883. },
  29884. enumerable: true,
  29885. configurable: true
  29886. });
  29887. Object.defineProperty(VertexBuffer, "ColorKind", {
  29888. get: function () {
  29889. return VertexBuffer._ColorKind;
  29890. },
  29891. enumerable: true,
  29892. configurable: true
  29893. });
  29894. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29895. get: function () {
  29896. return VertexBuffer._MatricesIndicesKind;
  29897. },
  29898. enumerable: true,
  29899. configurable: true
  29900. });
  29901. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29902. get: function () {
  29903. return VertexBuffer._MatricesWeightsKind;
  29904. },
  29905. enumerable: true,
  29906. configurable: true
  29907. });
  29908. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29909. get: function () {
  29910. return VertexBuffer._MatricesIndicesExtraKind;
  29911. },
  29912. enumerable: true,
  29913. configurable: true
  29914. });
  29915. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29916. get: function () {
  29917. return VertexBuffer._MatricesWeightsExtraKind;
  29918. },
  29919. enumerable: true,
  29920. configurable: true
  29921. });
  29922. /**
  29923. * Deduces the stride given a kind.
  29924. * @param kind The kind string to deduce
  29925. * @returns The deduced stride
  29926. */
  29927. VertexBuffer.DeduceStride = function (kind) {
  29928. switch (kind) {
  29929. case VertexBuffer.UVKind:
  29930. case VertexBuffer.UV2Kind:
  29931. case VertexBuffer.UV3Kind:
  29932. case VertexBuffer.UV4Kind:
  29933. case VertexBuffer.UV5Kind:
  29934. case VertexBuffer.UV6Kind:
  29935. return 2;
  29936. case VertexBuffer.NormalKind:
  29937. case VertexBuffer.PositionKind:
  29938. return 3;
  29939. case VertexBuffer.ColorKind:
  29940. case VertexBuffer.MatricesIndicesKind:
  29941. case VertexBuffer.MatricesIndicesExtraKind:
  29942. case VertexBuffer.MatricesWeightsKind:
  29943. case VertexBuffer.MatricesWeightsExtraKind:
  29944. case VertexBuffer.TangentKind:
  29945. return 4;
  29946. default:
  29947. throw new Error("Invalid kind '" + kind + "'");
  29948. }
  29949. };
  29950. /**
  29951. * Gets the byte length of the given type.
  29952. * @param type the type
  29953. * @returns the number of bytes
  29954. */
  29955. VertexBuffer.GetTypeByteLength = function (type) {
  29956. switch (type) {
  29957. case VertexBuffer.BYTE:
  29958. case VertexBuffer.UNSIGNED_BYTE:
  29959. return 1;
  29960. case VertexBuffer.SHORT:
  29961. case VertexBuffer.UNSIGNED_SHORT:
  29962. return 2;
  29963. case VertexBuffer.INT:
  29964. case VertexBuffer.FLOAT:
  29965. return 4;
  29966. default:
  29967. throw new Error("Invalid type '" + type + "'");
  29968. }
  29969. };
  29970. /**
  29971. * Enumerates each value of the given parameters as numbers.
  29972. * @param data the data to enumerate
  29973. * @param byteOffset the byte offset of the data
  29974. * @param byteStride the byte stride of the data
  29975. * @param componentCount the number of components per element
  29976. * @param componentType the type of the component
  29977. * @param count the total number of components
  29978. * @param normalized whether the data is normalized
  29979. * @param callback the callback function called for each value
  29980. */
  29981. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29982. if (data instanceof Array) {
  29983. var offset = byteOffset / 4;
  29984. var stride = byteStride / 4;
  29985. for (var index = 0; index < count; index += componentCount) {
  29986. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29987. callback(data[offset + componentIndex], index + componentIndex);
  29988. }
  29989. offset += stride;
  29990. }
  29991. }
  29992. else {
  29993. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29994. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29995. for (var index = 0; index < count; index += componentCount) {
  29996. var componentByteOffset = byteOffset;
  29997. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29998. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29999. callback(value, index + componentIndex);
  30000. componentByteOffset += componentByteLength;
  30001. }
  30002. byteOffset += byteStride;
  30003. }
  30004. }
  30005. };
  30006. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30007. switch (type) {
  30008. case VertexBuffer.BYTE: {
  30009. var value = dataView.getInt8(byteOffset);
  30010. if (normalized) {
  30011. value = Math.max(value / 127, -1);
  30012. }
  30013. return value;
  30014. }
  30015. case VertexBuffer.UNSIGNED_BYTE: {
  30016. var value = dataView.getUint8(byteOffset);
  30017. if (normalized) {
  30018. value = value / 255;
  30019. }
  30020. return value;
  30021. }
  30022. case VertexBuffer.SHORT: {
  30023. var value = dataView.getInt16(byteOffset, true);
  30024. if (normalized) {
  30025. value = Math.max(value / 16383, -1);
  30026. }
  30027. return value;
  30028. }
  30029. case VertexBuffer.UNSIGNED_SHORT: {
  30030. var value = dataView.getUint16(byteOffset, true);
  30031. if (normalized) {
  30032. value = value / 65535;
  30033. }
  30034. return value;
  30035. }
  30036. case VertexBuffer.FLOAT: {
  30037. return dataView.getFloat32(byteOffset, true);
  30038. }
  30039. default: {
  30040. throw new Error("Invalid component type " + type);
  30041. }
  30042. }
  30043. };
  30044. /**
  30045. * The byte type.
  30046. */
  30047. VertexBuffer.BYTE = 5120;
  30048. /**
  30049. * The unsigned byte type.
  30050. */
  30051. VertexBuffer.UNSIGNED_BYTE = 5121;
  30052. /**
  30053. * The short type.
  30054. */
  30055. VertexBuffer.SHORT = 5122;
  30056. /**
  30057. * The unsigned short type.
  30058. */
  30059. VertexBuffer.UNSIGNED_SHORT = 5123;
  30060. /**
  30061. * The integer type.
  30062. */
  30063. VertexBuffer.INT = 5124;
  30064. /**
  30065. * The unsigned integer type.
  30066. */
  30067. VertexBuffer.UNSIGNED_INT = 5125;
  30068. /**
  30069. * The float type.
  30070. */
  30071. VertexBuffer.FLOAT = 5126;
  30072. // Enums
  30073. VertexBuffer._PositionKind = "position";
  30074. VertexBuffer._NormalKind = "normal";
  30075. VertexBuffer._TangentKind = "tangent";
  30076. VertexBuffer._UVKind = "uv";
  30077. VertexBuffer._UV2Kind = "uv2";
  30078. VertexBuffer._UV3Kind = "uv3";
  30079. VertexBuffer._UV4Kind = "uv4";
  30080. VertexBuffer._UV5Kind = "uv5";
  30081. VertexBuffer._UV6Kind = "uv6";
  30082. VertexBuffer._ColorKind = "color";
  30083. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  30084. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  30085. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  30086. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  30087. return VertexBuffer;
  30088. }());
  30089. BABYLON.VertexBuffer = VertexBuffer;
  30090. })(BABYLON || (BABYLON = {}));
  30091. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30092. var BABYLON;
  30093. (function (BABYLON) {
  30094. /**
  30095. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30096. */
  30097. var DummyInternalTextureTracker = /** @class */ (function () {
  30098. function DummyInternalTextureTracker() {
  30099. /**
  30100. * Gets or set the previous tracker in the list
  30101. */
  30102. this.previous = null;
  30103. /**
  30104. * Gets or set the next tracker in the list
  30105. */
  30106. this.next = null;
  30107. }
  30108. return DummyInternalTextureTracker;
  30109. }());
  30110. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30111. })(BABYLON || (BABYLON = {}));
  30112. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30113. var BABYLON;
  30114. (function (BABYLON) {
  30115. /**
  30116. * Class used to store data associated with WebGL texture data for the engine
  30117. * This class should not be used directly
  30118. */
  30119. var InternalTexture = /** @class */ (function () {
  30120. /**
  30121. * Creates a new InternalTexture
  30122. * @param engine defines the engine to use
  30123. * @param dataSource defines the type of data that will be used
  30124. */
  30125. function InternalTexture(engine, dataSource) {
  30126. /**
  30127. * Observable called when the texture is loaded
  30128. */
  30129. this.onLoadedObservable = new BABYLON.Observable();
  30130. /**
  30131. * Gets or set the previous tracker in the list
  30132. */
  30133. this.previous = null;
  30134. /**
  30135. * Gets or set the next tracker in the list
  30136. */
  30137. this.next = null;
  30138. // Private
  30139. /** @hidden */
  30140. this._initialSlot = -1;
  30141. /** @hidden */
  30142. this._designatedSlot = -1;
  30143. /** @hidden */
  30144. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30145. /** @hidden */
  30146. this._comparisonFunction = 0;
  30147. /** @hidden */
  30148. this._lodGenerationScale = 0;
  30149. /** @hidden */
  30150. this._lodGenerationOffset = 0;
  30151. /** @hidden */
  30152. this._isRGBD = false;
  30153. /** @hidden */
  30154. this._references = 1;
  30155. this._engine = engine;
  30156. this._dataSource = dataSource;
  30157. this._webGLTexture = engine._createTexture();
  30158. }
  30159. /**
  30160. * Gets the Engine the texture belongs to.
  30161. * @returns The babylon engine
  30162. */
  30163. InternalTexture.prototype.getEngine = function () {
  30164. return this._engine;
  30165. };
  30166. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30167. /**
  30168. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30169. */
  30170. get: function () {
  30171. return this._dataSource;
  30172. },
  30173. enumerable: true,
  30174. configurable: true
  30175. });
  30176. /**
  30177. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30178. */
  30179. InternalTexture.prototype.incrementReferences = function () {
  30180. this._references++;
  30181. };
  30182. /**
  30183. * Change the size of the texture (not the size of the content)
  30184. * @param width defines the new width
  30185. * @param height defines the new height
  30186. * @param depth defines the new depth (1 by default)
  30187. */
  30188. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30189. if (depth === void 0) { depth = 1; }
  30190. this.width = width;
  30191. this.height = height;
  30192. this.depth = depth;
  30193. this.baseWidth = width;
  30194. this.baseHeight = height;
  30195. this.baseDepth = depth;
  30196. this._size = width * height * depth;
  30197. };
  30198. /** @hidden */
  30199. InternalTexture.prototype._rebuild = function () {
  30200. var _this = this;
  30201. var proxy;
  30202. this.isReady = false;
  30203. this._cachedCoordinatesMode = null;
  30204. this._cachedWrapU = null;
  30205. this._cachedWrapV = null;
  30206. this._cachedAnisotropicFilteringLevel = null;
  30207. switch (this._dataSource) {
  30208. case InternalTexture.DATASOURCE_TEMP:
  30209. return;
  30210. case InternalTexture.DATASOURCE_URL:
  30211. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30212. _this.isReady = true;
  30213. }, null, this._buffer, undefined, this.format);
  30214. proxy._swapAndDie(this);
  30215. return;
  30216. case InternalTexture.DATASOURCE_RAW:
  30217. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30218. proxy._swapAndDie(this);
  30219. this.isReady = true;
  30220. return;
  30221. case InternalTexture.DATASOURCE_RAW3D:
  30222. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30223. proxy._swapAndDie(this);
  30224. this.isReady = true;
  30225. return;
  30226. case InternalTexture.DATASOURCE_DYNAMIC:
  30227. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30228. proxy._swapAndDie(this);
  30229. // The engine will make sure to update content so no need to flag it as isReady = true
  30230. return;
  30231. case InternalTexture.DATASOURCE_RENDERTARGET:
  30232. var options = new BABYLON.RenderTargetCreationOptions();
  30233. options.generateDepthBuffer = this._generateDepthBuffer;
  30234. options.generateMipMaps = this.generateMipMaps;
  30235. options.generateStencilBuffer = this._generateStencilBuffer;
  30236. options.samplingMode = this.samplingMode;
  30237. options.type = this.type;
  30238. if (this.isCube) {
  30239. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30240. }
  30241. else {
  30242. var size = {
  30243. width: this.width,
  30244. height: this.height
  30245. };
  30246. proxy = this._engine.createRenderTargetTexture(size, options);
  30247. }
  30248. proxy._swapAndDie(this);
  30249. this.isReady = true;
  30250. return;
  30251. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30252. var depthTextureOptions = {
  30253. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30254. comparisonFunction: this._comparisonFunction,
  30255. generateStencil: this._generateStencilBuffer,
  30256. isCube: this.isCube
  30257. };
  30258. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30259. proxy._swapAndDie(this);
  30260. this.isReady = true;
  30261. return;
  30262. case InternalTexture.DATASOURCE_CUBE:
  30263. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30264. _this.isReady = true;
  30265. }, null, this.format, this._extension);
  30266. proxy._swapAndDie(this);
  30267. return;
  30268. case InternalTexture.DATASOURCE_CUBERAW:
  30269. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30270. proxy._swapAndDie(this);
  30271. this.isReady = true;
  30272. return;
  30273. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30274. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30275. if (proxy) {
  30276. proxy._swapAndDie(_this);
  30277. }
  30278. _this.isReady = true;
  30279. }, null, this.format, this._extension);
  30280. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30281. return;
  30282. }
  30283. };
  30284. InternalTexture.prototype._swapAndDie = function (target) {
  30285. target._webGLTexture = this._webGLTexture;
  30286. if (this._framebuffer) {
  30287. target._framebuffer = this._framebuffer;
  30288. }
  30289. if (this._depthStencilBuffer) {
  30290. target._depthStencilBuffer = this._depthStencilBuffer;
  30291. }
  30292. if (this._lodTextureHigh) {
  30293. if (target._lodTextureHigh) {
  30294. target._lodTextureHigh.dispose();
  30295. }
  30296. target._lodTextureHigh = this._lodTextureHigh;
  30297. }
  30298. if (this._lodTextureMid) {
  30299. if (target._lodTextureMid) {
  30300. target._lodTextureMid.dispose();
  30301. }
  30302. target._lodTextureMid = this._lodTextureMid;
  30303. }
  30304. if (this._lodTextureLow) {
  30305. if (target._lodTextureLow) {
  30306. target._lodTextureLow.dispose();
  30307. }
  30308. target._lodTextureLow = this._lodTextureLow;
  30309. }
  30310. var cache = this._engine.getLoadedTexturesCache();
  30311. var index = cache.indexOf(this);
  30312. if (index !== -1) {
  30313. cache.splice(index, 1);
  30314. }
  30315. };
  30316. /**
  30317. * Dispose the current allocated resources
  30318. */
  30319. InternalTexture.prototype.dispose = function () {
  30320. if (!this._webGLTexture) {
  30321. return;
  30322. }
  30323. this._references--;
  30324. if (this._references === 0) {
  30325. this._engine._releaseTexture(this);
  30326. this._webGLTexture = null;
  30327. this.previous = null;
  30328. this.next = null;
  30329. }
  30330. };
  30331. /**
  30332. * The source of the texture data is unknown
  30333. */
  30334. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30335. /**
  30336. * Texture data comes from an URL
  30337. */
  30338. InternalTexture.DATASOURCE_URL = 1;
  30339. /**
  30340. * Texture data is only used for temporary storage
  30341. */
  30342. InternalTexture.DATASOURCE_TEMP = 2;
  30343. /**
  30344. * Texture data comes from raw data (ArrayBuffer)
  30345. */
  30346. InternalTexture.DATASOURCE_RAW = 3;
  30347. /**
  30348. * Texture content is dynamic (video or dynamic texture)
  30349. */
  30350. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30351. /**
  30352. * Texture content is generated by rendering to it
  30353. */
  30354. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30355. /**
  30356. * Texture content is part of a multi render target process
  30357. */
  30358. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30359. /**
  30360. * Texture data comes from a cube data file
  30361. */
  30362. InternalTexture.DATASOURCE_CUBE = 7;
  30363. /**
  30364. * Texture data comes from a raw cube data
  30365. */
  30366. InternalTexture.DATASOURCE_CUBERAW = 8;
  30367. /**
  30368. * Texture data come from a prefiltered cube data file
  30369. */
  30370. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30371. /**
  30372. * Texture content is raw 3D data
  30373. */
  30374. InternalTexture.DATASOURCE_RAW3D = 10;
  30375. /**
  30376. * Texture content is a depth texture
  30377. */
  30378. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30379. return InternalTexture;
  30380. }());
  30381. BABYLON.InternalTexture = InternalTexture;
  30382. })(BABYLON || (BABYLON = {}));
  30383. //# sourceMappingURL=babylon.internalTexture.js.map
  30384. var BABYLON;
  30385. (function (BABYLON) {
  30386. var BaseTexture = /** @class */ (function () {
  30387. function BaseTexture(scene) {
  30388. this._hasAlpha = false;
  30389. this.getAlphaFromRGB = false;
  30390. this.level = 1;
  30391. this.coordinatesIndex = 0;
  30392. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30393. /**
  30394. * | Value | Type | Description |
  30395. * | ----- | ------------------ | ----------- |
  30396. * | 0 | CLAMP_ADDRESSMODE | |
  30397. * | 1 | WRAP_ADDRESSMODE | |
  30398. * | 2 | MIRROR_ADDRESSMODE | |
  30399. */
  30400. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30401. /**
  30402. * | Value | Type | Description |
  30403. * | ----- | ------------------ | ----------- |
  30404. * | 0 | CLAMP_ADDRESSMODE | |
  30405. * | 1 | WRAP_ADDRESSMODE | |
  30406. * | 2 | MIRROR_ADDRESSMODE | |
  30407. */
  30408. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30409. /**
  30410. * | Value | Type | Description |
  30411. * | ----- | ------------------ | ----------- |
  30412. * | 0 | CLAMP_ADDRESSMODE | |
  30413. * | 1 | WRAP_ADDRESSMODE | |
  30414. * | 2 | MIRROR_ADDRESSMODE | |
  30415. */
  30416. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30417. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30418. this.isCube = false;
  30419. this.is3D = false;
  30420. this.gammaSpace = true;
  30421. this.invertZ = false;
  30422. this.lodLevelInAlpha = false;
  30423. this.isRenderTarget = false;
  30424. this.animations = new Array();
  30425. /**
  30426. * An event triggered when the texture is disposed.
  30427. */
  30428. this.onDisposeObservable = new BABYLON.Observable();
  30429. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30430. this._cachedSize = BABYLON.Size.Zero();
  30431. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30432. if (this._scene) {
  30433. this._scene.textures.push(this);
  30434. }
  30435. this._uid = null;
  30436. }
  30437. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30438. get: function () {
  30439. return this._hasAlpha;
  30440. },
  30441. set: function (value) {
  30442. if (this._hasAlpha === value) {
  30443. return;
  30444. }
  30445. this._hasAlpha = value;
  30446. if (this._scene) {
  30447. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30448. }
  30449. },
  30450. enumerable: true,
  30451. configurable: true
  30452. });
  30453. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30454. get: function () {
  30455. return this._coordinatesMode;
  30456. },
  30457. /**
  30458. * How a texture is mapped.
  30459. *
  30460. * | Value | Type | Description |
  30461. * | ----- | ----------------------------------- | ----------- |
  30462. * | 0 | EXPLICIT_MODE | |
  30463. * | 1 | SPHERICAL_MODE | |
  30464. * | 2 | PLANAR_MODE | |
  30465. * | 3 | CUBIC_MODE | |
  30466. * | 4 | PROJECTION_MODE | |
  30467. * | 5 | SKYBOX_MODE | |
  30468. * | 6 | INVCUBIC_MODE | |
  30469. * | 7 | EQUIRECTANGULAR_MODE | |
  30470. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30471. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30472. */
  30473. set: function (value) {
  30474. if (this._coordinatesMode === value) {
  30475. return;
  30476. }
  30477. this._coordinatesMode = value;
  30478. if (this._scene) {
  30479. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30480. }
  30481. },
  30482. enumerable: true,
  30483. configurable: true
  30484. });
  30485. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30486. /**
  30487. * Gets whether or not the texture contains RGBD data.
  30488. */
  30489. get: function () {
  30490. return this._texture != null && this._texture._isRGBD;
  30491. },
  30492. enumerable: true,
  30493. configurable: true
  30494. });
  30495. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30496. get: function () {
  30497. if (this._texture)
  30498. return this._texture._lodGenerationOffset;
  30499. return 0.0;
  30500. },
  30501. set: function (value) {
  30502. if (this._texture)
  30503. this._texture._lodGenerationOffset = value;
  30504. },
  30505. enumerable: true,
  30506. configurable: true
  30507. });
  30508. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30509. get: function () {
  30510. if (this._texture)
  30511. return this._texture._lodGenerationScale;
  30512. return 0.0;
  30513. },
  30514. set: function (value) {
  30515. if (this._texture)
  30516. this._texture._lodGenerationScale = value;
  30517. },
  30518. enumerable: true,
  30519. configurable: true
  30520. });
  30521. Object.defineProperty(BaseTexture.prototype, "uid", {
  30522. get: function () {
  30523. if (!this._uid) {
  30524. this._uid = BABYLON.Tools.RandomId();
  30525. }
  30526. return this._uid;
  30527. },
  30528. enumerable: true,
  30529. configurable: true
  30530. });
  30531. BaseTexture.prototype.toString = function () {
  30532. return this.name;
  30533. };
  30534. BaseTexture.prototype.getClassName = function () {
  30535. return "BaseTexture";
  30536. };
  30537. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30538. set: function (callback) {
  30539. if (this._onDisposeObserver) {
  30540. this.onDisposeObservable.remove(this._onDisposeObserver);
  30541. }
  30542. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30543. },
  30544. enumerable: true,
  30545. configurable: true
  30546. });
  30547. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30548. get: function () {
  30549. return true;
  30550. },
  30551. enumerable: true,
  30552. configurable: true
  30553. });
  30554. BaseTexture.prototype.getScene = function () {
  30555. return this._scene;
  30556. };
  30557. BaseTexture.prototype.getTextureMatrix = function () {
  30558. return BABYLON.Matrix.IdentityReadOnly;
  30559. };
  30560. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30561. return BABYLON.Matrix.IdentityReadOnly;
  30562. };
  30563. BaseTexture.prototype.getInternalTexture = function () {
  30564. return this._texture;
  30565. };
  30566. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30567. return !this.isBlocking || this.isReady();
  30568. };
  30569. BaseTexture.prototype.isReady = function () {
  30570. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30571. this.delayLoad();
  30572. return false;
  30573. }
  30574. if (this._texture) {
  30575. return this._texture.isReady;
  30576. }
  30577. return false;
  30578. };
  30579. BaseTexture.prototype.getSize = function () {
  30580. if (this._texture) {
  30581. if (this._texture.width) {
  30582. this._cachedSize.width = this._texture.width;
  30583. this._cachedSize.height = this._texture.height;
  30584. return this._cachedSize;
  30585. }
  30586. if (this._texture._size) {
  30587. this._cachedSize.width = this._texture._size;
  30588. this._cachedSize.height = this._texture._size;
  30589. return this._cachedSize;
  30590. }
  30591. }
  30592. return this._cachedSize;
  30593. };
  30594. BaseTexture.prototype.getBaseSize = function () {
  30595. if (!this.isReady() || !this._texture)
  30596. return BABYLON.Size.Zero();
  30597. if (this._texture._size) {
  30598. return new BABYLON.Size(this._texture._size, this._texture._size);
  30599. }
  30600. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30601. };
  30602. BaseTexture.prototype.scale = function (ratio) {
  30603. };
  30604. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30605. get: function () {
  30606. return false;
  30607. },
  30608. enumerable: true,
  30609. configurable: true
  30610. });
  30611. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30612. if (!this._scene) {
  30613. return null;
  30614. }
  30615. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30616. for (var index = 0; index < texturesCache.length; index++) {
  30617. var texturesCacheEntry = texturesCache[index];
  30618. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30619. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30620. texturesCacheEntry.incrementReferences();
  30621. return texturesCacheEntry;
  30622. }
  30623. }
  30624. }
  30625. return null;
  30626. };
  30627. BaseTexture.prototype._rebuild = function () {
  30628. };
  30629. BaseTexture.prototype.delayLoad = function () {
  30630. };
  30631. BaseTexture.prototype.clone = function () {
  30632. return null;
  30633. };
  30634. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30635. get: function () {
  30636. if (!this._texture) {
  30637. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30638. }
  30639. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30640. },
  30641. enumerable: true,
  30642. configurable: true
  30643. });
  30644. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30645. get: function () {
  30646. if (!this._texture) {
  30647. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30648. }
  30649. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30650. },
  30651. enumerable: true,
  30652. configurable: true
  30653. });
  30654. /**
  30655. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30656. * This will returns an RGBA array buffer containing either in values (0-255) or
  30657. * float values (0-1) depending of the underlying buffer type.
  30658. * @param faceIndex The face of the texture to read (in case of cube texture)
  30659. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30660. * @returns The Array buffer containing the pixels data.
  30661. */
  30662. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30663. if (faceIndex === void 0) { faceIndex = 0; }
  30664. if (level === void 0) { level = 0; }
  30665. if (!this._texture) {
  30666. return null;
  30667. }
  30668. var size = this.getSize();
  30669. var width = size.width;
  30670. var height = size.height;
  30671. var scene = this.getScene();
  30672. if (!scene) {
  30673. return null;
  30674. }
  30675. var engine = scene.getEngine();
  30676. if (level != 0) {
  30677. width = width / Math.pow(2, level);
  30678. height = height / Math.pow(2, level);
  30679. width = Math.round(width);
  30680. height = Math.round(height);
  30681. }
  30682. if (this._texture.isCube) {
  30683. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30684. }
  30685. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30686. };
  30687. BaseTexture.prototype.releaseInternalTexture = function () {
  30688. if (this._texture) {
  30689. this._texture.dispose();
  30690. this._texture = null;
  30691. }
  30692. };
  30693. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30694. get: function () {
  30695. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30696. return null;
  30697. }
  30698. if (!this._texture._sphericalPolynomial) {
  30699. this._texture._sphericalPolynomial =
  30700. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30701. }
  30702. return this._texture._sphericalPolynomial;
  30703. },
  30704. set: function (value) {
  30705. if (this._texture) {
  30706. this._texture._sphericalPolynomial = value;
  30707. }
  30708. },
  30709. enumerable: true,
  30710. configurable: true
  30711. });
  30712. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30713. get: function () {
  30714. if (this._texture) {
  30715. return this._texture._lodTextureHigh;
  30716. }
  30717. return null;
  30718. },
  30719. enumerable: true,
  30720. configurable: true
  30721. });
  30722. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30723. get: function () {
  30724. if (this._texture) {
  30725. return this._texture._lodTextureMid;
  30726. }
  30727. return null;
  30728. },
  30729. enumerable: true,
  30730. configurable: true
  30731. });
  30732. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30733. get: function () {
  30734. if (this._texture) {
  30735. return this._texture._lodTextureLow;
  30736. }
  30737. return null;
  30738. },
  30739. enumerable: true,
  30740. configurable: true
  30741. });
  30742. BaseTexture.prototype.dispose = function () {
  30743. if (!this._scene) {
  30744. return;
  30745. }
  30746. // Animations
  30747. this._scene.stopAnimation(this);
  30748. // Remove from scene
  30749. this._scene._removePendingData(this);
  30750. var index = this._scene.textures.indexOf(this);
  30751. if (index >= 0) {
  30752. this._scene.textures.splice(index, 1);
  30753. }
  30754. if (this._texture === undefined) {
  30755. return;
  30756. }
  30757. // Release
  30758. this.releaseInternalTexture();
  30759. // Callback
  30760. this.onDisposeObservable.notifyObservers(this);
  30761. this.onDisposeObservable.clear();
  30762. };
  30763. BaseTexture.prototype.serialize = function () {
  30764. if (!this.name) {
  30765. return null;
  30766. }
  30767. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30768. // Animations
  30769. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30770. return serializationObject;
  30771. };
  30772. BaseTexture.WhenAllReady = function (textures, callback) {
  30773. var numRemaining = textures.length;
  30774. if (numRemaining === 0) {
  30775. callback();
  30776. return;
  30777. }
  30778. var _loop_1 = function () {
  30779. texture = textures[i];
  30780. if (texture.isReady()) {
  30781. if (--numRemaining === 0) {
  30782. callback();
  30783. }
  30784. }
  30785. else {
  30786. onLoadObservable = texture.onLoadObservable;
  30787. var onLoadCallback_1 = function () {
  30788. onLoadObservable.removeCallback(onLoadCallback_1);
  30789. if (--numRemaining === 0) {
  30790. callback();
  30791. }
  30792. };
  30793. onLoadObservable.add(onLoadCallback_1);
  30794. }
  30795. };
  30796. var texture, onLoadObservable;
  30797. for (var i = 0; i < textures.length; i++) {
  30798. _loop_1();
  30799. }
  30800. };
  30801. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30802. __decorate([
  30803. BABYLON.serialize()
  30804. ], BaseTexture.prototype, "name", void 0);
  30805. __decorate([
  30806. BABYLON.serialize("hasAlpha")
  30807. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30808. __decorate([
  30809. BABYLON.serialize()
  30810. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30811. __decorate([
  30812. BABYLON.serialize()
  30813. ], BaseTexture.prototype, "level", void 0);
  30814. __decorate([
  30815. BABYLON.serialize()
  30816. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30817. __decorate([
  30818. BABYLON.serialize("coordinatesMode")
  30819. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30820. __decorate([
  30821. BABYLON.serialize()
  30822. ], BaseTexture.prototype, "wrapU", void 0);
  30823. __decorate([
  30824. BABYLON.serialize()
  30825. ], BaseTexture.prototype, "wrapV", void 0);
  30826. __decorate([
  30827. BABYLON.serialize()
  30828. ], BaseTexture.prototype, "wrapR", void 0);
  30829. __decorate([
  30830. BABYLON.serialize()
  30831. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30832. __decorate([
  30833. BABYLON.serialize()
  30834. ], BaseTexture.prototype, "isCube", void 0);
  30835. __decorate([
  30836. BABYLON.serialize()
  30837. ], BaseTexture.prototype, "is3D", void 0);
  30838. __decorate([
  30839. BABYLON.serialize()
  30840. ], BaseTexture.prototype, "gammaSpace", void 0);
  30841. __decorate([
  30842. BABYLON.serialize()
  30843. ], BaseTexture.prototype, "invertZ", void 0);
  30844. __decorate([
  30845. BABYLON.serialize()
  30846. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30847. __decorate([
  30848. BABYLON.serialize()
  30849. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30850. __decorate([
  30851. BABYLON.serialize()
  30852. ], BaseTexture.prototype, "lodGenerationScale", null);
  30853. __decorate([
  30854. BABYLON.serialize()
  30855. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30856. return BaseTexture;
  30857. }());
  30858. BABYLON.BaseTexture = BaseTexture;
  30859. })(BABYLON || (BABYLON = {}));
  30860. //# sourceMappingURL=babylon.baseTexture.js.map
  30861. var BABYLON;
  30862. (function (BABYLON) {
  30863. var Texture = /** @class */ (function (_super) {
  30864. __extends(Texture, _super);
  30865. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30866. if (noMipmap === void 0) { noMipmap = false; }
  30867. if (invertY === void 0) { invertY = true; }
  30868. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30869. if (onLoad === void 0) { onLoad = null; }
  30870. if (onError === void 0) { onError = null; }
  30871. if (buffer === void 0) { buffer = null; }
  30872. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30873. var _this = _super.call(this, scene) || this;
  30874. _this.uOffset = 0;
  30875. _this.vOffset = 0;
  30876. _this.uScale = 1.0;
  30877. _this.vScale = 1.0;
  30878. _this.uAng = 0;
  30879. _this.vAng = 0;
  30880. _this.wAng = 0;
  30881. /**
  30882. * Defines the center of rotation (U)
  30883. */
  30884. _this.uRotationCenter = 0.5;
  30885. /**
  30886. * Defines the center of rotation (V)
  30887. */
  30888. _this.vRotationCenter = 0.5;
  30889. /**
  30890. * Defines the center of rotation (W)
  30891. */
  30892. _this.wRotationCenter = 0.5;
  30893. _this._isBlocking = true;
  30894. _this.name = url || "";
  30895. _this.url = url;
  30896. _this._noMipmap = noMipmap;
  30897. _this._invertY = invertY;
  30898. _this._samplingMode = samplingMode;
  30899. _this._buffer = buffer;
  30900. _this._deleteBuffer = deleteBuffer;
  30901. if (format) {
  30902. _this._format = format;
  30903. }
  30904. scene = _this.getScene();
  30905. if (!scene) {
  30906. return _this;
  30907. }
  30908. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30909. var load = function () {
  30910. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30911. _this.onLoadObservable.notifyObservers(_this);
  30912. }
  30913. if (onLoad) {
  30914. onLoad();
  30915. }
  30916. if (!_this.isBlocking && scene) {
  30917. scene.resetCachedMaterial();
  30918. }
  30919. };
  30920. if (!_this.url) {
  30921. _this._delayedOnLoad = load;
  30922. _this._delayedOnError = onError;
  30923. return _this;
  30924. }
  30925. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30926. if (!_this._texture) {
  30927. if (!scene.useDelayedTextureLoading) {
  30928. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30929. if (deleteBuffer) {
  30930. delete _this._buffer;
  30931. }
  30932. }
  30933. else {
  30934. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30935. _this._delayedOnLoad = load;
  30936. _this._delayedOnError = onError;
  30937. }
  30938. }
  30939. else {
  30940. if (_this._texture.isReady) {
  30941. BABYLON.Tools.SetImmediate(function () { return load(); });
  30942. }
  30943. else {
  30944. _this._texture.onLoadedObservable.add(load);
  30945. }
  30946. }
  30947. return _this;
  30948. }
  30949. Object.defineProperty(Texture.prototype, "noMipmap", {
  30950. get: function () {
  30951. return this._noMipmap;
  30952. },
  30953. enumerable: true,
  30954. configurable: true
  30955. });
  30956. Object.defineProperty(Texture.prototype, "isBlocking", {
  30957. get: function () {
  30958. return this._isBlocking;
  30959. },
  30960. set: function (value) {
  30961. this._isBlocking = value;
  30962. },
  30963. enumerable: true,
  30964. configurable: true
  30965. });
  30966. Object.defineProperty(Texture.prototype, "samplingMode", {
  30967. get: function () {
  30968. return this._samplingMode;
  30969. },
  30970. enumerable: true,
  30971. configurable: true
  30972. });
  30973. /**
  30974. * Update the url (and optional buffer) of this texture if url was null during construction.
  30975. * @param url the url of the texture
  30976. * @param buffer the buffer of the texture (defaults to null)
  30977. */
  30978. Texture.prototype.updateURL = function (url, buffer) {
  30979. if (buffer === void 0) { buffer = null; }
  30980. if (this.url) {
  30981. throw new Error("URL is already set");
  30982. }
  30983. this.url = url;
  30984. this._buffer = buffer;
  30985. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30986. this.delayLoad();
  30987. };
  30988. Texture.prototype.delayLoad = function () {
  30989. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30990. return;
  30991. }
  30992. var scene = this.getScene();
  30993. if (!scene) {
  30994. return;
  30995. }
  30996. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30997. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30998. if (!this._texture) {
  30999. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31000. if (this._deleteBuffer) {
  31001. delete this._buffer;
  31002. }
  31003. }
  31004. else {
  31005. if (this._delayedOnLoad) {
  31006. if (this._texture.isReady) {
  31007. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31008. }
  31009. else {
  31010. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31011. }
  31012. }
  31013. }
  31014. this._delayedOnLoad = null;
  31015. this._delayedOnError = null;
  31016. };
  31017. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31018. if (!this._texture) {
  31019. return;
  31020. }
  31021. var scene = this.getScene();
  31022. if (!scene) {
  31023. return;
  31024. }
  31025. this._samplingMode = samplingMode;
  31026. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31027. };
  31028. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31029. x *= this.uScale;
  31030. y *= this.vScale;
  31031. x -= this.uRotationCenter * this.uScale;
  31032. y -= this.vRotationCenter * this.vScale;
  31033. z -= this.wRotationCenter;
  31034. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31035. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31036. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31037. t.z += this.wRotationCenter;
  31038. };
  31039. Texture.prototype.getTextureMatrix = function () {
  31040. var _this = this;
  31041. if (this.uOffset === this._cachedUOffset &&
  31042. this.vOffset === this._cachedVOffset &&
  31043. this.uScale === this._cachedUScale &&
  31044. this.vScale === this._cachedVScale &&
  31045. this.uAng === this._cachedUAng &&
  31046. this.vAng === this._cachedVAng &&
  31047. this.wAng === this._cachedWAng) {
  31048. return this._cachedTextureMatrix;
  31049. }
  31050. this._cachedUOffset = this.uOffset;
  31051. this._cachedVOffset = this.vOffset;
  31052. this._cachedUScale = this.uScale;
  31053. this._cachedVScale = this.vScale;
  31054. this._cachedUAng = this.uAng;
  31055. this._cachedVAng = this.vAng;
  31056. this._cachedWAng = this.wAng;
  31057. if (!this._cachedTextureMatrix) {
  31058. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31059. this._rowGenerationMatrix = new BABYLON.Matrix();
  31060. this._t0 = BABYLON.Vector3.Zero();
  31061. this._t1 = BABYLON.Vector3.Zero();
  31062. this._t2 = BABYLON.Vector3.Zero();
  31063. }
  31064. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31065. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31066. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31067. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31068. this._t1.subtractInPlace(this._t0);
  31069. this._t2.subtractInPlace(this._t0);
  31070. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31071. this._cachedTextureMatrix.m[0] = this._t1.x;
  31072. this._cachedTextureMatrix.m[1] = this._t1.y;
  31073. this._cachedTextureMatrix.m[2] = this._t1.z;
  31074. this._cachedTextureMatrix.m[4] = this._t2.x;
  31075. this._cachedTextureMatrix.m[5] = this._t2.y;
  31076. this._cachedTextureMatrix.m[6] = this._t2.z;
  31077. this._cachedTextureMatrix.m[8] = this._t0.x;
  31078. this._cachedTextureMatrix.m[9] = this._t0.y;
  31079. this._cachedTextureMatrix.m[10] = this._t0.z;
  31080. var scene = this.getScene();
  31081. if (!scene) {
  31082. return this._cachedTextureMatrix;
  31083. }
  31084. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31085. return mat.hasTexture(_this);
  31086. });
  31087. return this._cachedTextureMatrix;
  31088. };
  31089. Texture.prototype.getReflectionTextureMatrix = function () {
  31090. var _this = this;
  31091. var scene = this.getScene();
  31092. if (!scene) {
  31093. return this._cachedTextureMatrix;
  31094. }
  31095. if (this.uOffset === this._cachedUOffset &&
  31096. this.vOffset === this._cachedVOffset &&
  31097. this.uScale === this._cachedUScale &&
  31098. this.vScale === this._cachedVScale &&
  31099. this.coordinatesMode === this._cachedCoordinatesMode) {
  31100. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31101. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31102. return this._cachedTextureMatrix;
  31103. }
  31104. }
  31105. else {
  31106. return this._cachedTextureMatrix;
  31107. }
  31108. }
  31109. if (!this._cachedTextureMatrix) {
  31110. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31111. }
  31112. if (!this._projectionModeMatrix) {
  31113. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31114. }
  31115. this._cachedUOffset = this.uOffset;
  31116. this._cachedVOffset = this.vOffset;
  31117. this._cachedUScale = this.uScale;
  31118. this._cachedVScale = this.vScale;
  31119. this._cachedCoordinatesMode = this.coordinatesMode;
  31120. switch (this.coordinatesMode) {
  31121. case Texture.PLANAR_MODE:
  31122. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31123. this._cachedTextureMatrix[0] = this.uScale;
  31124. this._cachedTextureMatrix[5] = this.vScale;
  31125. this._cachedTextureMatrix[12] = this.uOffset;
  31126. this._cachedTextureMatrix[13] = this.vOffset;
  31127. break;
  31128. case Texture.PROJECTION_MODE:
  31129. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31130. this._projectionModeMatrix.m[0] = 0.5;
  31131. this._projectionModeMatrix.m[5] = -0.5;
  31132. this._projectionModeMatrix.m[10] = 0.0;
  31133. this._projectionModeMatrix.m[12] = 0.5;
  31134. this._projectionModeMatrix.m[13] = 0.5;
  31135. this._projectionModeMatrix.m[14] = 1.0;
  31136. this._projectionModeMatrix.m[15] = 1.0;
  31137. var projectionMatrix = scene.getProjectionMatrix();
  31138. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31139. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31140. break;
  31141. default:
  31142. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31143. break;
  31144. }
  31145. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31146. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31147. });
  31148. return this._cachedTextureMatrix;
  31149. };
  31150. Texture.prototype.clone = function () {
  31151. var _this = this;
  31152. return BABYLON.SerializationHelper.Clone(function () {
  31153. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31154. }, this);
  31155. };
  31156. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31157. get: function () {
  31158. if (!this._onLoadObservable) {
  31159. this._onLoadObservable = new BABYLON.Observable();
  31160. }
  31161. return this._onLoadObservable;
  31162. },
  31163. enumerable: true,
  31164. configurable: true
  31165. });
  31166. Texture.prototype.serialize = function () {
  31167. var serializationObject = _super.prototype.serialize.call(this);
  31168. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31169. serializationObject.base64String = this._buffer;
  31170. serializationObject.name = serializationObject.name.replace("data:", "");
  31171. }
  31172. serializationObject.invertY = this._invertY;
  31173. serializationObject.samplingMode = this.samplingMode;
  31174. return serializationObject;
  31175. };
  31176. Texture.prototype.getClassName = function () {
  31177. return "Texture";
  31178. };
  31179. Texture.prototype.dispose = function () {
  31180. _super.prototype.dispose.call(this);
  31181. if (this._onLoadObservable) {
  31182. this._onLoadObservable.clear();
  31183. this._onLoadObservable = null;
  31184. }
  31185. this._delayedOnLoad = null;
  31186. this._delayedOnError = null;
  31187. };
  31188. // Statics
  31189. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31190. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31191. if (onLoad === void 0) { onLoad = null; }
  31192. if (onError === void 0) { onError = null; }
  31193. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31194. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31195. };
  31196. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31197. if (parsedTexture.customType) {
  31198. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31199. // Update Sampling Mode
  31200. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31201. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31202. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31203. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31204. }
  31205. }
  31206. return parsedCustomTexture;
  31207. }
  31208. if (parsedTexture.isCube) {
  31209. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31210. }
  31211. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31212. return null;
  31213. }
  31214. var texture = BABYLON.SerializationHelper.Parse(function () {
  31215. var generateMipMaps = true;
  31216. if (parsedTexture.noMipmap) {
  31217. generateMipMaps = false;
  31218. }
  31219. if (parsedTexture.mirrorPlane) {
  31220. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31221. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31222. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31223. return mirrorTexture;
  31224. }
  31225. else if (parsedTexture.isRenderTarget) {
  31226. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31227. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31228. return renderTargetTexture;
  31229. }
  31230. else {
  31231. var texture;
  31232. if (parsedTexture.base64String) {
  31233. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31234. }
  31235. else {
  31236. var url = rootUrl + parsedTexture.name;
  31237. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31238. url = parsedTexture.url;
  31239. }
  31240. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31241. }
  31242. return texture;
  31243. }
  31244. }, parsedTexture, scene);
  31245. // Update Sampling Mode
  31246. if (parsedTexture.samplingMode) {
  31247. var sampling = parsedTexture.samplingMode;
  31248. if (texture._samplingMode !== sampling) {
  31249. texture.updateSamplingMode(sampling);
  31250. }
  31251. }
  31252. // Animations
  31253. if (parsedTexture.animations) {
  31254. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31255. var parsedAnimation = parsedTexture.animations[animationIndex];
  31256. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31257. }
  31258. }
  31259. return texture;
  31260. };
  31261. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31262. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31263. if (noMipmap === void 0) { noMipmap = false; }
  31264. if (invertY === void 0) { invertY = true; }
  31265. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31266. if (onLoad === void 0) { onLoad = null; }
  31267. if (onError === void 0) { onError = null; }
  31268. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31269. if (name.substr(0, 5) !== "data:") {
  31270. name = "data:" + name;
  31271. }
  31272. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31273. };
  31274. // Constants
  31275. Texture.NEAREST_SAMPLINGMODE = 1;
  31276. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31277. Texture.BILINEAR_SAMPLINGMODE = 2;
  31278. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31279. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31280. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31281. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31282. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31283. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31284. Texture.NEAREST_LINEAR = 7;
  31285. Texture.NEAREST_NEAREST = 8;
  31286. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31287. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31288. Texture.LINEAR_LINEAR = 11;
  31289. Texture.LINEAR_NEAREST = 12;
  31290. Texture.EXPLICIT_MODE = 0;
  31291. Texture.SPHERICAL_MODE = 1;
  31292. Texture.PLANAR_MODE = 2;
  31293. Texture.CUBIC_MODE = 3;
  31294. Texture.PROJECTION_MODE = 4;
  31295. Texture.SKYBOX_MODE = 5;
  31296. Texture.INVCUBIC_MODE = 6;
  31297. Texture.EQUIRECTANGULAR_MODE = 7;
  31298. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31299. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31300. Texture.CLAMP_ADDRESSMODE = 0;
  31301. Texture.WRAP_ADDRESSMODE = 1;
  31302. Texture.MIRROR_ADDRESSMODE = 2;
  31303. /**
  31304. * 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
  31305. */
  31306. Texture.UseSerializedUrlIfAny = false;
  31307. __decorate([
  31308. BABYLON.serialize()
  31309. ], Texture.prototype, "url", void 0);
  31310. __decorate([
  31311. BABYLON.serialize()
  31312. ], Texture.prototype, "uOffset", void 0);
  31313. __decorate([
  31314. BABYLON.serialize()
  31315. ], Texture.prototype, "vOffset", void 0);
  31316. __decorate([
  31317. BABYLON.serialize()
  31318. ], Texture.prototype, "uScale", void 0);
  31319. __decorate([
  31320. BABYLON.serialize()
  31321. ], Texture.prototype, "vScale", void 0);
  31322. __decorate([
  31323. BABYLON.serialize()
  31324. ], Texture.prototype, "uAng", void 0);
  31325. __decorate([
  31326. BABYLON.serialize()
  31327. ], Texture.prototype, "vAng", void 0);
  31328. __decorate([
  31329. BABYLON.serialize()
  31330. ], Texture.prototype, "wAng", void 0);
  31331. __decorate([
  31332. BABYLON.serialize()
  31333. ], Texture.prototype, "uRotationCenter", void 0);
  31334. __decorate([
  31335. BABYLON.serialize()
  31336. ], Texture.prototype, "vRotationCenter", void 0);
  31337. __decorate([
  31338. BABYLON.serialize()
  31339. ], Texture.prototype, "wRotationCenter", void 0);
  31340. __decorate([
  31341. BABYLON.serialize()
  31342. ], Texture.prototype, "isBlocking", null);
  31343. return Texture;
  31344. }(BABYLON.BaseTexture));
  31345. BABYLON.Texture = Texture;
  31346. })(BABYLON || (BABYLON = {}));
  31347. //# sourceMappingURL=babylon.texture.js.map
  31348. var BABYLON;
  31349. (function (BABYLON) {
  31350. /**
  31351. * @hidden
  31352. **/
  31353. var _InstancesBatch = /** @class */ (function () {
  31354. function _InstancesBatch() {
  31355. this.mustReturn = false;
  31356. this.visibleInstances = new Array();
  31357. this.renderSelf = new Array();
  31358. }
  31359. return _InstancesBatch;
  31360. }());
  31361. BABYLON._InstancesBatch = _InstancesBatch;
  31362. var Mesh = /** @class */ (function (_super) {
  31363. __extends(Mesh, _super);
  31364. /**
  31365. * @constructor
  31366. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31367. * @param {Scene} scene The scene to add this mesh to.
  31368. * @param {Node} parent The parent of this mesh, if it has one
  31369. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31370. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31371. * When false, achieved by calling a clone(), also passing False.
  31372. * This will make creation of children, recursive.
  31373. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31374. */
  31375. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31376. if (scene === void 0) { scene = null; }
  31377. if (parent === void 0) { parent = null; }
  31378. if (source === void 0) { source = null; }
  31379. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31380. var _this = _super.call(this, name, scene) || this;
  31381. // Events
  31382. /**
  31383. * An event triggered before rendering the mesh
  31384. */
  31385. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31386. /**
  31387. * An event triggered after rendering the mesh
  31388. */
  31389. _this.onAfterRenderObservable = new BABYLON.Observable();
  31390. /**
  31391. * An event triggered before drawing the mesh
  31392. */
  31393. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31394. // Members
  31395. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31396. _this.instances = new Array();
  31397. _this._LODLevels = new Array();
  31398. _this._visibleInstances = {};
  31399. _this._renderIdForInstances = new Array();
  31400. _this._batchCache = new _InstancesBatch();
  31401. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31402. // Use by builder only to know what orientation were the mesh build in.
  31403. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31404. _this.overrideMaterialSideOrientation = null;
  31405. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31406. // Will be used to save a source mesh reference, If any
  31407. _this._source = null;
  31408. scene = _this.getScene();
  31409. if (source) {
  31410. // Geometry
  31411. if (source._geometry) {
  31412. source._geometry.applyToMesh(_this);
  31413. }
  31414. // Deep copy
  31415. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31416. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31417. // Source mesh
  31418. _this._source = source;
  31419. // Metadata
  31420. if (source.metadata && source.metadata.clone) {
  31421. _this.metadata = source.metadata.clone();
  31422. }
  31423. else {
  31424. _this.metadata = source.metadata;
  31425. }
  31426. // Tags
  31427. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31428. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31429. }
  31430. // Parent
  31431. _this.parent = source.parent;
  31432. // Pivot
  31433. _this.setPivotMatrix(source.getPivotMatrix());
  31434. _this.id = name + "." + source.id;
  31435. // Material
  31436. _this.material = source.material;
  31437. var index;
  31438. if (!doNotCloneChildren) {
  31439. // Children
  31440. var directDescendants = source.getDescendants(true);
  31441. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31442. var child = directDescendants[index_1];
  31443. if (child.clone) {
  31444. child.clone(name + "." + child.name, _this);
  31445. }
  31446. }
  31447. }
  31448. // Physics clone
  31449. var physicsEngine = _this.getScene().getPhysicsEngine();
  31450. if (clonePhysicsImpostor && physicsEngine) {
  31451. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31452. if (impostor) {
  31453. _this.physicsImpostor = impostor.clone(_this);
  31454. }
  31455. }
  31456. // Particles
  31457. for (index = 0; index < scene.particleSystems.length; index++) {
  31458. var system = scene.particleSystems[index];
  31459. if (system.emitter === source) {
  31460. system.clone(system.name, _this);
  31461. }
  31462. }
  31463. _this.refreshBoundingInfo();
  31464. _this.computeWorldMatrix(true);
  31465. }
  31466. // Parent
  31467. if (parent !== null) {
  31468. _this.parent = parent;
  31469. }
  31470. return _this;
  31471. }
  31472. Object.defineProperty(Mesh, "FRONTSIDE", {
  31473. /**
  31474. * Mesh side orientation : usually the external or front surface
  31475. */
  31476. get: function () {
  31477. return Mesh._FRONTSIDE;
  31478. },
  31479. enumerable: true,
  31480. configurable: true
  31481. });
  31482. Object.defineProperty(Mesh, "BACKSIDE", {
  31483. /**
  31484. * Mesh side orientation : usually the internal or back surface
  31485. */
  31486. get: function () {
  31487. return Mesh._BACKSIDE;
  31488. },
  31489. enumerable: true,
  31490. configurable: true
  31491. });
  31492. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31493. /**
  31494. * Mesh side orientation : both internal and external or front and back surfaces
  31495. */
  31496. get: function () {
  31497. return Mesh._DOUBLESIDE;
  31498. },
  31499. enumerable: true,
  31500. configurable: true
  31501. });
  31502. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31503. /**
  31504. * Mesh side orientation : by default, `FRONTSIDE`
  31505. */
  31506. get: function () {
  31507. return Mesh._DEFAULTSIDE;
  31508. },
  31509. enumerable: true,
  31510. configurable: true
  31511. });
  31512. Object.defineProperty(Mesh, "NO_CAP", {
  31513. /**
  31514. * Mesh cap setting : no cap
  31515. */
  31516. get: function () {
  31517. return Mesh._NO_CAP;
  31518. },
  31519. enumerable: true,
  31520. configurable: true
  31521. });
  31522. Object.defineProperty(Mesh, "CAP_START", {
  31523. /**
  31524. * Mesh cap setting : one cap at the beginning of the mesh
  31525. */
  31526. get: function () {
  31527. return Mesh._CAP_START;
  31528. },
  31529. enumerable: true,
  31530. configurable: true
  31531. });
  31532. Object.defineProperty(Mesh, "CAP_END", {
  31533. /**
  31534. * Mesh cap setting : one cap at the end of the mesh
  31535. */
  31536. get: function () {
  31537. return Mesh._CAP_END;
  31538. },
  31539. enumerable: true,
  31540. configurable: true
  31541. });
  31542. Object.defineProperty(Mesh, "CAP_ALL", {
  31543. /**
  31544. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31545. */
  31546. get: function () {
  31547. return Mesh._CAP_ALL;
  31548. },
  31549. enumerable: true,
  31550. configurable: true
  31551. });
  31552. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31553. set: function (callback) {
  31554. if (this._onBeforeDrawObserver) {
  31555. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31556. }
  31557. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31558. },
  31559. enumerable: true,
  31560. configurable: true
  31561. });
  31562. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31563. get: function () {
  31564. return this._morphTargetManager;
  31565. },
  31566. set: function (value) {
  31567. if (this._morphTargetManager === value) {
  31568. return;
  31569. }
  31570. this._morphTargetManager = value;
  31571. this._syncGeometryWithMorphTargetManager();
  31572. },
  31573. enumerable: true,
  31574. configurable: true
  31575. });
  31576. Object.defineProperty(Mesh.prototype, "source", {
  31577. get: function () {
  31578. return this._source;
  31579. },
  31580. enumerable: true,
  31581. configurable: true
  31582. });
  31583. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31584. get: function () {
  31585. return this._unIndexed;
  31586. },
  31587. set: function (value) {
  31588. if (this._unIndexed !== value) {
  31589. this._unIndexed = value;
  31590. this._markSubMeshesAsAttributesDirty();
  31591. }
  31592. },
  31593. enumerable: true,
  31594. configurable: true
  31595. });
  31596. // Methods
  31597. /**
  31598. * Returns the string "Mesh".
  31599. */
  31600. Mesh.prototype.getClassName = function () {
  31601. return "Mesh";
  31602. };
  31603. /**
  31604. * Returns a string.
  31605. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31606. */
  31607. Mesh.prototype.toString = function (fullDetails) {
  31608. var ret = _super.prototype.toString.call(this, fullDetails);
  31609. ret += ", n vertices: " + this.getTotalVertices();
  31610. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31611. if (this.animations) {
  31612. for (var i = 0; i < this.animations.length; i++) {
  31613. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31614. }
  31615. }
  31616. if (fullDetails) {
  31617. if (this._geometry) {
  31618. var ib = this.getIndices();
  31619. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31620. if (vb && ib) {
  31621. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31622. }
  31623. }
  31624. else {
  31625. ret += ", flat shading: UNKNOWN";
  31626. }
  31627. }
  31628. return ret;
  31629. };
  31630. Mesh.prototype._unBindEffect = function () {
  31631. _super.prototype._unBindEffect.call(this);
  31632. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31633. var instance = _a[_i];
  31634. instance._unBindEffect();
  31635. }
  31636. };
  31637. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31638. /**
  31639. * True if the mesh has some Levels Of Details (LOD).
  31640. * Returns a boolean.
  31641. */
  31642. get: function () {
  31643. return this._LODLevels.length > 0;
  31644. },
  31645. enumerable: true,
  31646. configurable: true
  31647. });
  31648. /**
  31649. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31650. * @returns an array of {BABYLON.MeshLODLevel}
  31651. */
  31652. Mesh.prototype.getLODLevels = function () {
  31653. return this._LODLevels;
  31654. };
  31655. Mesh.prototype._sortLODLevels = function () {
  31656. this._LODLevels.sort(function (a, b) {
  31657. if (a.distance < b.distance) {
  31658. return 1;
  31659. }
  31660. if (a.distance > b.distance) {
  31661. return -1;
  31662. }
  31663. return 0;
  31664. });
  31665. };
  31666. /**
  31667. * Add a mesh as LOD level triggered at the given distance.
  31668. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31669. * @param distance The distance from the center of the object to show this level
  31670. * @param mesh The mesh to be added as LOD level (can be null)
  31671. * @return This mesh (for chaining)
  31672. */
  31673. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31674. if (mesh && mesh._masterMesh) {
  31675. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31676. return this;
  31677. }
  31678. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31679. this._LODLevels.push(level);
  31680. if (mesh) {
  31681. mesh._masterMesh = this;
  31682. }
  31683. this._sortLODLevels();
  31684. return this;
  31685. };
  31686. /**
  31687. * Returns the LOD level mesh at the passed distance or null if not found.
  31688. * It is related to the method `addLODLevel(distance, mesh)`.
  31689. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31690. * Returns an object Mesh or `null`.
  31691. */
  31692. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31693. for (var index = 0; index < this._LODLevels.length; index++) {
  31694. var level = this._LODLevels[index];
  31695. if (level.distance === distance) {
  31696. return level.mesh;
  31697. }
  31698. }
  31699. return null;
  31700. };
  31701. /**
  31702. * Remove a mesh from the LOD array
  31703. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31704. * @param {Mesh} mesh The mesh to be removed.
  31705. * @return {Mesh} This mesh (for chaining)
  31706. */
  31707. Mesh.prototype.removeLODLevel = function (mesh) {
  31708. for (var index = 0; index < this._LODLevels.length; index++) {
  31709. if (this._LODLevels[index].mesh === mesh) {
  31710. this._LODLevels.splice(index, 1);
  31711. if (mesh) {
  31712. mesh._masterMesh = null;
  31713. }
  31714. }
  31715. }
  31716. this._sortLODLevels();
  31717. return this;
  31718. };
  31719. /**
  31720. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31721. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31722. */
  31723. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31724. if (!this._LODLevels || this._LODLevels.length === 0) {
  31725. return this;
  31726. }
  31727. var bSphere;
  31728. if (boundingSphere) {
  31729. bSphere = boundingSphere;
  31730. }
  31731. else {
  31732. var boundingInfo = this.getBoundingInfo();
  31733. bSphere = boundingInfo.boundingSphere;
  31734. }
  31735. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31736. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31737. if (this.onLODLevelSelection) {
  31738. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31739. }
  31740. return this;
  31741. }
  31742. for (var index = 0; index < this._LODLevels.length; index++) {
  31743. var level = this._LODLevels[index];
  31744. if (level.distance < distanceToCamera) {
  31745. if (level.mesh) {
  31746. level.mesh._preActivate();
  31747. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31748. }
  31749. if (this.onLODLevelSelection) {
  31750. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31751. }
  31752. return level.mesh;
  31753. }
  31754. }
  31755. if (this.onLODLevelSelection) {
  31756. this.onLODLevelSelection(distanceToCamera, this, this);
  31757. }
  31758. return this;
  31759. };
  31760. Object.defineProperty(Mesh.prototype, "geometry", {
  31761. /**
  31762. * Returns the mesh internal Geometry object.
  31763. */
  31764. get: function () {
  31765. return this._geometry;
  31766. },
  31767. enumerable: true,
  31768. configurable: true
  31769. });
  31770. /**
  31771. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31772. */
  31773. Mesh.prototype.getTotalVertices = function () {
  31774. if (this._geometry === null || this._geometry === undefined) {
  31775. return 0;
  31776. }
  31777. return this._geometry.getTotalVertices();
  31778. };
  31779. /**
  31780. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31781. * 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.
  31782. * You can force the copy with forceCopy === true
  31783. * Returns null if the mesh has no geometry or no vertex buffer.
  31784. * Possible `kind` values :
  31785. * - BABYLON.VertexBuffer.PositionKind
  31786. * - BABYLON.VertexBuffer.UVKind
  31787. * - BABYLON.VertexBuffer.UV2Kind
  31788. * - BABYLON.VertexBuffer.UV3Kind
  31789. * - BABYLON.VertexBuffer.UV4Kind
  31790. * - BABYLON.VertexBuffer.UV5Kind
  31791. * - BABYLON.VertexBuffer.UV6Kind
  31792. * - BABYLON.VertexBuffer.ColorKind
  31793. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31794. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31795. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31796. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31797. */
  31798. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31799. if (!this._geometry) {
  31800. return null;
  31801. }
  31802. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31803. };
  31804. /**
  31805. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31806. * Returns `null` if the mesh has no geometry.
  31807. * Possible `kind` values :
  31808. * - BABYLON.VertexBuffer.PositionKind
  31809. * - BABYLON.VertexBuffer.UVKind
  31810. * - BABYLON.VertexBuffer.UV2Kind
  31811. * - BABYLON.VertexBuffer.UV3Kind
  31812. * - BABYLON.VertexBuffer.UV4Kind
  31813. * - BABYLON.VertexBuffer.UV5Kind
  31814. * - BABYLON.VertexBuffer.UV6Kind
  31815. * - BABYLON.VertexBuffer.ColorKind
  31816. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31817. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31818. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31819. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31820. */
  31821. Mesh.prototype.getVertexBuffer = function (kind) {
  31822. if (!this._geometry) {
  31823. return null;
  31824. }
  31825. return this._geometry.getVertexBuffer(kind);
  31826. };
  31827. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31828. if (!this._geometry) {
  31829. if (this._delayInfo) {
  31830. return this._delayInfo.indexOf(kind) !== -1;
  31831. }
  31832. return false;
  31833. }
  31834. return this._geometry.isVerticesDataPresent(kind);
  31835. };
  31836. /**
  31837. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31838. * Possible `kind` values :
  31839. * - BABYLON.VertexBuffer.PositionKind
  31840. * - BABYLON.VertexBuffer.UVKind
  31841. * - BABYLON.VertexBuffer.UV2Kind
  31842. * - BABYLON.VertexBuffer.UV3Kind
  31843. * - BABYLON.VertexBuffer.UV4Kind
  31844. * - BABYLON.VertexBuffer.UV5Kind
  31845. * - BABYLON.VertexBuffer.UV6Kind
  31846. * - BABYLON.VertexBuffer.ColorKind
  31847. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31848. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31849. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31850. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31851. */
  31852. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31853. if (!this._geometry) {
  31854. if (this._delayInfo) {
  31855. return this._delayInfo.indexOf(kind) !== -1;
  31856. }
  31857. return false;
  31858. }
  31859. return this._geometry.isVertexBufferUpdatable(kind);
  31860. };
  31861. /**
  31862. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31863. * Possible `kind` values :
  31864. * - BABYLON.VertexBuffer.PositionKind
  31865. * - BABYLON.VertexBuffer.UVKind
  31866. * - BABYLON.VertexBuffer.UV2Kind
  31867. * - BABYLON.VertexBuffer.UV3Kind
  31868. * - BABYLON.VertexBuffer.UV4Kind
  31869. * - BABYLON.VertexBuffer.UV5Kind
  31870. * - BABYLON.VertexBuffer.UV6Kind
  31871. * - BABYLON.VertexBuffer.ColorKind
  31872. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31873. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31874. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31875. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31876. */
  31877. Mesh.prototype.getVerticesDataKinds = function () {
  31878. if (!this._geometry) {
  31879. var result = new Array();
  31880. if (this._delayInfo) {
  31881. this._delayInfo.forEach(function (kind, index, array) {
  31882. result.push(kind);
  31883. });
  31884. }
  31885. return result;
  31886. }
  31887. return this._geometry.getVerticesDataKinds();
  31888. };
  31889. /**
  31890. * Returns a positive integer : the total number of indices in this mesh geometry.
  31891. * Returns zero if the mesh has no geometry.
  31892. */
  31893. Mesh.prototype.getTotalIndices = function () {
  31894. if (!this._geometry) {
  31895. return 0;
  31896. }
  31897. return this._geometry.getTotalIndices();
  31898. };
  31899. /**
  31900. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31901. * 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.
  31902. * Returns an empty array if the mesh has no geometry.
  31903. */
  31904. Mesh.prototype.getIndices = function (copyWhenShared) {
  31905. if (!this._geometry) {
  31906. return [];
  31907. }
  31908. return this._geometry.getIndices(copyWhenShared);
  31909. };
  31910. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31911. get: function () {
  31912. return this._masterMesh !== null && this._masterMesh !== undefined;
  31913. },
  31914. enumerable: true,
  31915. configurable: true
  31916. });
  31917. /**
  31918. * Determine if the current mesh is ready to be rendered
  31919. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31920. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31921. * @returns true if all associated assets are ready (material, textures, shaders)
  31922. */
  31923. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31924. if (completeCheck === void 0) { completeCheck = false; }
  31925. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31926. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31927. return false;
  31928. }
  31929. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31930. return false;
  31931. }
  31932. if (!this.subMeshes || this.subMeshes.length === 0) {
  31933. return true;
  31934. }
  31935. if (!completeCheck) {
  31936. return true;
  31937. }
  31938. var engine = this.getEngine();
  31939. var scene = this.getScene();
  31940. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31941. this.computeWorldMatrix();
  31942. var mat = this.material || scene.defaultMaterial;
  31943. if (mat) {
  31944. if (mat.storeEffectOnSubMeshes) {
  31945. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31946. var subMesh = _a[_i];
  31947. var effectiveMaterial = subMesh.getMaterial();
  31948. if (effectiveMaterial) {
  31949. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31950. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31951. return false;
  31952. }
  31953. }
  31954. else {
  31955. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31956. return false;
  31957. }
  31958. }
  31959. }
  31960. }
  31961. }
  31962. else {
  31963. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31964. return false;
  31965. }
  31966. }
  31967. }
  31968. // Shadows
  31969. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31970. var light = _c[_b];
  31971. var generator = light.getShadowGenerator();
  31972. if (generator) {
  31973. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31974. var subMesh = _e[_d];
  31975. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31976. return false;
  31977. }
  31978. }
  31979. }
  31980. }
  31981. // LOD
  31982. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31983. var lod = _g[_f];
  31984. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31985. return false;
  31986. }
  31987. }
  31988. return true;
  31989. };
  31990. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31991. /**
  31992. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31993. * This property is pertinent only for updatable parametric shapes.
  31994. */
  31995. get: function () {
  31996. return this._areNormalsFrozen;
  31997. },
  31998. enumerable: true,
  31999. configurable: true
  32000. });
  32001. /**
  32002. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32003. * It has no effect at all on other shapes.
  32004. * It prevents the mesh normals from being recomputed on next `positions` array update.
  32005. * Returns the Mesh.
  32006. */
  32007. Mesh.prototype.freezeNormals = function () {
  32008. this._areNormalsFrozen = true;
  32009. return this;
  32010. };
  32011. /**
  32012. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32013. * It has no effect at all on other shapes.
  32014. * It reactivates the mesh normals computation if it was previously frozen.
  32015. * Returns the Mesh.
  32016. */
  32017. Mesh.prototype.unfreezeNormals = function () {
  32018. this._areNormalsFrozen = false;
  32019. return this;
  32020. };
  32021. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32022. /**
  32023. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32024. */
  32025. set: function (count) {
  32026. this._overridenInstanceCount = count;
  32027. },
  32028. enumerable: true,
  32029. configurable: true
  32030. });
  32031. // Methods
  32032. Mesh.prototype._preActivate = function () {
  32033. var sceneRenderId = this.getScene().getRenderId();
  32034. if (this._preActivateId === sceneRenderId) {
  32035. return this;
  32036. }
  32037. this._preActivateId = sceneRenderId;
  32038. this._visibleInstances = null;
  32039. return this;
  32040. };
  32041. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32042. if (this._visibleInstances) {
  32043. this._visibleInstances.intermediateDefaultRenderId = renderId;
  32044. }
  32045. return this;
  32046. };
  32047. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32048. if (!this._visibleInstances) {
  32049. this._visibleInstances = {};
  32050. this._visibleInstances.defaultRenderId = renderId;
  32051. this._visibleInstances.selfDefaultRenderId = this._renderId;
  32052. }
  32053. if (!this._visibleInstances[renderId]) {
  32054. this._visibleInstances[renderId] = new Array();
  32055. }
  32056. this._visibleInstances[renderId].push(instance);
  32057. return this;
  32058. };
  32059. /**
  32060. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32061. * This means the mesh underlying bounding box and sphere are recomputed.
  32062. * Returns the Mesh.
  32063. */
  32064. Mesh.prototype.refreshBoundingInfo = function () {
  32065. return this._refreshBoundingInfo(false);
  32066. };
  32067. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32068. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32069. return this;
  32070. }
  32071. var data = this._getPositionData(applySkeleton);
  32072. if (data) {
  32073. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  32074. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32075. }
  32076. if (this.subMeshes) {
  32077. for (var index = 0; index < this.subMeshes.length; index++) {
  32078. this.subMeshes[index].refreshBoundingInfo();
  32079. }
  32080. }
  32081. this._updateBoundingInfo();
  32082. return this;
  32083. };
  32084. Mesh.prototype._getPositionData = function (applySkeleton) {
  32085. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32086. if (data && applySkeleton && this.skeleton) {
  32087. data = BABYLON.Tools.Slice(data);
  32088. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32089. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32090. if (matricesWeightsData && matricesIndicesData) {
  32091. var needExtras = this.numBoneInfluencers > 4;
  32092. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32093. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32094. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32095. var tempVector = BABYLON.Tmp.Vector3[0];
  32096. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32097. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32098. var matWeightIdx = 0;
  32099. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32100. finalMatrix.reset();
  32101. var inf;
  32102. var weight;
  32103. for (inf = 0; inf < 4; inf++) {
  32104. weight = matricesWeightsData[matWeightIdx + inf];
  32105. if (weight <= 0)
  32106. break;
  32107. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32108. finalMatrix.addToSelf(tempMatrix);
  32109. }
  32110. if (needExtras) {
  32111. for (inf = 0; inf < 4; inf++) {
  32112. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32113. if (weight <= 0)
  32114. break;
  32115. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32116. finalMatrix.addToSelf(tempMatrix);
  32117. }
  32118. }
  32119. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32120. tempVector.toArray(data, index);
  32121. }
  32122. }
  32123. }
  32124. return data;
  32125. };
  32126. Mesh.prototype._createGlobalSubMesh = function (force) {
  32127. var totalVertices = this.getTotalVertices();
  32128. if (!totalVertices || !this.getIndices()) {
  32129. return null;
  32130. }
  32131. // Check if we need to recreate the submeshes
  32132. if (this.subMeshes && this.subMeshes.length > 0) {
  32133. var ib = this.getIndices();
  32134. if (!ib) {
  32135. return null;
  32136. }
  32137. var totalIndices = ib.length;
  32138. var needToRecreate = false;
  32139. if (force) {
  32140. needToRecreate = true;
  32141. }
  32142. else {
  32143. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32144. var submesh = _a[_i];
  32145. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32146. needToRecreate = true;
  32147. break;
  32148. }
  32149. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32150. needToRecreate = true;
  32151. break;
  32152. }
  32153. }
  32154. }
  32155. if (!needToRecreate) {
  32156. return this.subMeshes[0];
  32157. }
  32158. }
  32159. this.releaseSubMeshes();
  32160. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32161. };
  32162. Mesh.prototype.subdivide = function (count) {
  32163. if (count < 1) {
  32164. return;
  32165. }
  32166. var totalIndices = this.getTotalIndices();
  32167. var subdivisionSize = (totalIndices / count) | 0;
  32168. var offset = 0;
  32169. // Ensure that subdivisionSize is a multiple of 3
  32170. while (subdivisionSize % 3 !== 0) {
  32171. subdivisionSize++;
  32172. }
  32173. this.releaseSubMeshes();
  32174. for (var index = 0; index < count; index++) {
  32175. if (offset >= totalIndices) {
  32176. break;
  32177. }
  32178. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32179. offset += subdivisionSize;
  32180. }
  32181. this.synchronizeInstances();
  32182. };
  32183. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32184. if (updatable === void 0) { updatable = false; }
  32185. if (!this._geometry) {
  32186. var vertexData = new BABYLON.VertexData();
  32187. vertexData.set(data, kind);
  32188. var scene = this.getScene();
  32189. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32190. }
  32191. else {
  32192. this._geometry.setVerticesData(kind, data, updatable, stride);
  32193. }
  32194. return this;
  32195. };
  32196. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32197. if (updatable === void 0) { updatable = true; }
  32198. var vb = this.getVertexBuffer(kind);
  32199. if (!vb || vb.isUpdatable() === updatable) {
  32200. return;
  32201. }
  32202. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32203. };
  32204. /**
  32205. * Sets the mesh VertexBuffer.
  32206. * Returns the Mesh.
  32207. */
  32208. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32209. if (!this._geometry) {
  32210. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32211. }
  32212. this._geometry.setVerticesBuffer(buffer);
  32213. return this;
  32214. };
  32215. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32216. if (!this._geometry) {
  32217. return this;
  32218. }
  32219. if (!makeItUnique) {
  32220. this._geometry.updateVerticesData(kind, data, updateExtends);
  32221. }
  32222. else {
  32223. this.makeGeometryUnique();
  32224. this.updateVerticesData(kind, data, updateExtends, false);
  32225. }
  32226. return this;
  32227. };
  32228. /**
  32229. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32230. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32231. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32232. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32233. * Returns the Mesh.
  32234. */
  32235. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32236. if (computeNormals === void 0) { computeNormals = true; }
  32237. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32238. if (!positions) {
  32239. return this;
  32240. }
  32241. positionFunction(positions);
  32242. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32243. if (computeNormals) {
  32244. var indices = this.getIndices();
  32245. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32246. if (!normals) {
  32247. return this;
  32248. }
  32249. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32250. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32251. }
  32252. return this;
  32253. };
  32254. /**
  32255. * Creates a un-shared specific occurence of the geometry for the mesh.
  32256. * Returns the Mesh.
  32257. */
  32258. Mesh.prototype.makeGeometryUnique = function () {
  32259. if (!this._geometry) {
  32260. return this;
  32261. }
  32262. var oldGeometry = this._geometry;
  32263. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32264. oldGeometry.releaseForMesh(this, true);
  32265. geometry.applyToMesh(this);
  32266. return this;
  32267. };
  32268. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32269. if (totalVertices === void 0) { totalVertices = null; }
  32270. if (updatable === void 0) { updatable = false; }
  32271. if (!this._geometry) {
  32272. var vertexData = new BABYLON.VertexData();
  32273. vertexData.indices = indices;
  32274. var scene = this.getScene();
  32275. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32276. }
  32277. else {
  32278. this._geometry.setIndices(indices, totalVertices, updatable);
  32279. }
  32280. return this;
  32281. };
  32282. /**
  32283. * Update the current index buffer
  32284. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32285. * Returns the Mesh.
  32286. */
  32287. Mesh.prototype.updateIndices = function (indices, offset) {
  32288. if (!this._geometry) {
  32289. return this;
  32290. }
  32291. this._geometry.updateIndices(indices, offset);
  32292. return this;
  32293. };
  32294. /**
  32295. * Invert the geometry to move from a right handed system to a left handed one.
  32296. * Returns the Mesh.
  32297. */
  32298. Mesh.prototype.toLeftHanded = function () {
  32299. if (!this._geometry) {
  32300. return this;
  32301. }
  32302. this._geometry.toLeftHanded();
  32303. return this;
  32304. };
  32305. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32306. if (!this._geometry) {
  32307. return this;
  32308. }
  32309. var engine = this.getScene().getEngine();
  32310. // Wireframe
  32311. var indexToBind;
  32312. if (this._unIndexed) {
  32313. indexToBind = null;
  32314. }
  32315. else {
  32316. switch (fillMode) {
  32317. case BABYLON.Material.PointFillMode:
  32318. indexToBind = null;
  32319. break;
  32320. case BABYLON.Material.WireFrameFillMode:
  32321. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32322. break;
  32323. default:
  32324. case BABYLON.Material.TriangleFillMode:
  32325. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32326. break;
  32327. }
  32328. }
  32329. // VBOs
  32330. this._geometry._bind(effect, indexToBind);
  32331. return this;
  32332. };
  32333. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32334. if (alternate === void 0) { alternate = false; }
  32335. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32336. return this;
  32337. }
  32338. this.onBeforeDrawObservable.notifyObservers(this);
  32339. var scene = this.getScene();
  32340. var engine = scene.getEngine();
  32341. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32342. // or triangles as points
  32343. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32344. }
  32345. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32346. // Triangles as wireframe
  32347. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32348. }
  32349. else {
  32350. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32351. }
  32352. if (scene._isAlternateRenderingEnabled && !alternate) {
  32353. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32354. if (!effect || !scene.activeCamera) {
  32355. return this;
  32356. }
  32357. scene._switchToAlternateCameraConfiguration(true);
  32358. this._effectiveMaterial.bindView(effect);
  32359. this._effectiveMaterial.bindViewProjection(effect);
  32360. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32361. this._draw(subMesh, fillMode, instancesCount, true);
  32362. engine.setViewport(scene.activeCamera.viewport);
  32363. scene._switchToAlternateCameraConfiguration(false);
  32364. this._effectiveMaterial.bindView(effect);
  32365. this._effectiveMaterial.bindViewProjection(effect);
  32366. }
  32367. return this;
  32368. };
  32369. /**
  32370. * Registers for this mesh a javascript function called just before the rendering process.
  32371. * This function is passed the current mesh.
  32372. * Return the Mesh.
  32373. */
  32374. Mesh.prototype.registerBeforeRender = function (func) {
  32375. this.onBeforeRenderObservable.add(func);
  32376. return this;
  32377. };
  32378. /**
  32379. * Disposes a previously registered javascript function called before the rendering.
  32380. * This function is passed the current mesh.
  32381. * Returns the Mesh.
  32382. */
  32383. Mesh.prototype.unregisterBeforeRender = function (func) {
  32384. this.onBeforeRenderObservable.removeCallback(func);
  32385. return this;
  32386. };
  32387. /**
  32388. * Registers for this mesh a javascript function called just after the rendering is complete.
  32389. * This function is passed the current mesh.
  32390. * Returns the Mesh.
  32391. */
  32392. Mesh.prototype.registerAfterRender = function (func) {
  32393. this.onAfterRenderObservable.add(func);
  32394. return this;
  32395. };
  32396. /**
  32397. * Disposes a previously registered javascript function called after the rendering.
  32398. * This function is passed the current mesh.
  32399. * Return the Mesh.
  32400. */
  32401. Mesh.prototype.unregisterAfterRender = function (func) {
  32402. this.onAfterRenderObservable.removeCallback(func);
  32403. return this;
  32404. };
  32405. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32406. var scene = this.getScene();
  32407. this._batchCache.mustReturn = false;
  32408. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32409. this._batchCache.visibleInstances[subMeshId] = null;
  32410. if (this._visibleInstances) {
  32411. var currentRenderId = scene.getRenderId();
  32412. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32413. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32414. var selfRenderId = this._renderId;
  32415. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32416. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32417. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32418. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32419. }
  32420. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32421. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32422. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32423. this._batchCache.mustReturn = true;
  32424. return this._batchCache;
  32425. }
  32426. if (currentRenderId !== selfRenderId) {
  32427. this._batchCache.renderSelf[subMeshId] = false;
  32428. }
  32429. }
  32430. this._renderIdForInstances[subMeshId] = currentRenderId;
  32431. }
  32432. return this._batchCache;
  32433. };
  32434. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32435. var visibleInstances = batch.visibleInstances[subMesh._id];
  32436. if (!visibleInstances) {
  32437. return this;
  32438. }
  32439. var matricesCount = visibleInstances.length + 1;
  32440. var bufferSize = matricesCount * 16 * 4;
  32441. var currentInstancesBufferSize = this._instancesBufferSize;
  32442. var instancesBuffer = this._instancesBuffer;
  32443. while (this._instancesBufferSize < bufferSize) {
  32444. this._instancesBufferSize *= 2;
  32445. }
  32446. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32447. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32448. }
  32449. var offset = 0;
  32450. var instancesCount = 0;
  32451. var world = this.getWorldMatrix();
  32452. if (batch.renderSelf[subMesh._id]) {
  32453. world.copyToArray(this._instancesData, offset);
  32454. offset += 16;
  32455. instancesCount++;
  32456. }
  32457. if (visibleInstances) {
  32458. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32459. var instance = visibleInstances[instanceIndex];
  32460. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32461. offset += 16;
  32462. instancesCount++;
  32463. }
  32464. }
  32465. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32466. if (instancesBuffer) {
  32467. instancesBuffer.dispose();
  32468. }
  32469. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32470. this._instancesBuffer = instancesBuffer;
  32471. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32472. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32473. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32474. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32475. }
  32476. else {
  32477. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32478. }
  32479. this._bind(subMesh, effect, fillMode);
  32480. this._draw(subMesh, fillMode, instancesCount);
  32481. engine.unbindInstanceAttributes();
  32482. return this;
  32483. };
  32484. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32485. var scene = this.getScene();
  32486. var engine = scene.getEngine();
  32487. if (hardwareInstancedRendering) {
  32488. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32489. }
  32490. else {
  32491. if (batch.renderSelf[subMesh._id]) {
  32492. // Draw
  32493. if (onBeforeDraw) {
  32494. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32495. }
  32496. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32497. }
  32498. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32499. if (visibleInstancesForSubMesh) {
  32500. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32501. var instance = visibleInstancesForSubMesh[instanceIndex];
  32502. // World
  32503. var world = instance.getWorldMatrix();
  32504. if (onBeforeDraw) {
  32505. onBeforeDraw(true, world, effectiveMaterial);
  32506. }
  32507. // Draw
  32508. this._draw(subMesh, fillMode);
  32509. }
  32510. }
  32511. }
  32512. return this;
  32513. };
  32514. /**
  32515. * Triggers the draw call for the mesh.
  32516. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32517. * Returns the Mesh.
  32518. */
  32519. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32520. this._checkOcclusionQuery();
  32521. if (this._isOccluded) {
  32522. return this;
  32523. }
  32524. var scene = this.getScene();
  32525. // Managing instances
  32526. var batch = this._getInstancesRenderList(subMesh._id);
  32527. if (batch.mustReturn) {
  32528. return this;
  32529. }
  32530. // Checking geometry state
  32531. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32532. return this;
  32533. }
  32534. this.onBeforeRenderObservable.notifyObservers(this);
  32535. var engine = scene.getEngine();
  32536. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32537. // Material
  32538. var material = subMesh.getMaterial();
  32539. if (!material) {
  32540. return this;
  32541. }
  32542. this._effectiveMaterial = material;
  32543. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32544. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32545. return this;
  32546. }
  32547. }
  32548. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32549. return this;
  32550. }
  32551. // Alpha mode
  32552. if (enableAlphaMode) {
  32553. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32554. }
  32555. // Outline - step 1
  32556. var savedDepthWrite = engine.getDepthWrite();
  32557. if (this.renderOutline) {
  32558. engine.setDepthWrite(false);
  32559. scene.getOutlineRenderer().render(subMesh, batch);
  32560. engine.setDepthWrite(savedDepthWrite);
  32561. }
  32562. var effect;
  32563. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32564. effect = subMesh.effect;
  32565. }
  32566. else {
  32567. effect = this._effectiveMaterial.getEffect();
  32568. }
  32569. if (!effect) {
  32570. return this;
  32571. }
  32572. var sideOrientation = this.overrideMaterialSideOrientation;
  32573. if (sideOrientation == null) {
  32574. sideOrientation = this._effectiveMaterial.sideOrientation;
  32575. if (this._getWorldMatrixDeterminant() < 0) {
  32576. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32577. }
  32578. }
  32579. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32580. if (this._effectiveMaterial.forceDepthWrite) {
  32581. engine.setDepthWrite(true);
  32582. }
  32583. // Bind
  32584. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32585. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32586. this._bind(subMesh, effect, fillMode);
  32587. }
  32588. var world = this.getWorldMatrix();
  32589. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32590. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32591. }
  32592. else {
  32593. this._effectiveMaterial.bind(world, this);
  32594. }
  32595. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32596. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32597. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32598. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32599. }
  32600. // Draw
  32601. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32602. // Unbind
  32603. this._effectiveMaterial.unbind();
  32604. // Outline - step 2
  32605. if (this.renderOutline && savedDepthWrite) {
  32606. engine.setDepthWrite(true);
  32607. engine.setColorWrite(false);
  32608. scene.getOutlineRenderer().render(subMesh, batch);
  32609. engine.setColorWrite(true);
  32610. }
  32611. // Overlay
  32612. if (this.renderOverlay) {
  32613. var currentMode = engine.getAlphaMode();
  32614. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32615. scene.getOutlineRenderer().render(subMesh, batch, true);
  32616. engine.setAlphaMode(currentMode);
  32617. }
  32618. this.onAfterRenderObservable.notifyObservers(this);
  32619. return this;
  32620. };
  32621. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32622. if (isInstance && effectiveMaterial) {
  32623. effectiveMaterial.bindOnlyWorldMatrix(world);
  32624. }
  32625. };
  32626. /**
  32627. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32628. */
  32629. Mesh.prototype.getEmittedParticleSystems = function () {
  32630. var results = new Array();
  32631. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32632. var particleSystem = this.getScene().particleSystems[index];
  32633. if (particleSystem.emitter === this) {
  32634. results.push(particleSystem);
  32635. }
  32636. }
  32637. return results;
  32638. };
  32639. /**
  32640. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32641. */
  32642. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32643. var results = new Array();
  32644. var descendants = this.getDescendants();
  32645. descendants.push(this);
  32646. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32647. var particleSystem = this.getScene().particleSystems[index];
  32648. var emitter = particleSystem.emitter;
  32649. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32650. results.push(particleSystem);
  32651. }
  32652. }
  32653. return results;
  32654. };
  32655. /**
  32656. * Normalize matrix weights so that all vertices have a total weight set to 1
  32657. */
  32658. Mesh.prototype.cleanMatrixWeights = function () {
  32659. var epsilon = 1e-3;
  32660. var noInfluenceBoneIndex = 0.0;
  32661. if (this.skeleton) {
  32662. noInfluenceBoneIndex = this.skeleton.bones.length;
  32663. }
  32664. else {
  32665. return;
  32666. }
  32667. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32668. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32669. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32670. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32671. var influencers = this.numBoneInfluencers;
  32672. var size = matricesWeights.length;
  32673. for (var i = 0; i < size; i += 4) {
  32674. var weight = 0.0;
  32675. var firstZeroWeight = -1;
  32676. for (var j = 0; j < 4; j++) {
  32677. var w = matricesWeights[i + j];
  32678. weight += w;
  32679. if (w < epsilon && firstZeroWeight < 0) {
  32680. firstZeroWeight = j;
  32681. }
  32682. }
  32683. if (matricesWeightsExtra) {
  32684. for (var j = 0; j < 4; j++) {
  32685. var w = matricesWeightsExtra[i + j];
  32686. weight += w;
  32687. if (w < epsilon && firstZeroWeight < 0) {
  32688. firstZeroWeight = j + 4;
  32689. }
  32690. }
  32691. }
  32692. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32693. firstZeroWeight = influencers - 1;
  32694. }
  32695. if (weight > epsilon) {
  32696. var mweight = 1.0 / weight;
  32697. for (var j = 0; j < 4; j++) {
  32698. matricesWeights[i + j] *= mweight;
  32699. }
  32700. if (matricesWeightsExtra) {
  32701. for (var j = 0; j < 4; j++) {
  32702. matricesWeightsExtra[i + j] *= mweight;
  32703. }
  32704. }
  32705. }
  32706. else {
  32707. if (firstZeroWeight >= 4) {
  32708. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32709. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32710. }
  32711. else {
  32712. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32713. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32714. }
  32715. }
  32716. }
  32717. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32718. if (matricesIndicesExtra) {
  32719. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32720. }
  32721. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32722. if (matricesWeightsExtra) {
  32723. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32724. }
  32725. };
  32726. Mesh.prototype._checkDelayState = function () {
  32727. var scene = this.getScene();
  32728. if (this._geometry) {
  32729. this._geometry.load(scene);
  32730. }
  32731. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32732. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32733. this._queueLoad(scene);
  32734. }
  32735. return this;
  32736. };
  32737. Mesh.prototype._queueLoad = function (scene) {
  32738. var _this = this;
  32739. scene._addPendingData(this);
  32740. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32741. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32742. if (data instanceof ArrayBuffer) {
  32743. _this._delayLoadingFunction(data, _this);
  32744. }
  32745. else {
  32746. _this._delayLoadingFunction(JSON.parse(data), _this);
  32747. }
  32748. _this.instances.forEach(function (instance) {
  32749. instance._syncSubMeshes();
  32750. });
  32751. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32752. scene._removePendingData(_this);
  32753. }, function () { }, scene.database, getBinaryData);
  32754. return this;
  32755. };
  32756. /**
  32757. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32758. */
  32759. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32760. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32761. return false;
  32762. }
  32763. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32764. return false;
  32765. }
  32766. this._checkDelayState();
  32767. return true;
  32768. };
  32769. /**
  32770. * Sets the mesh material by the material or multiMaterial `id` property.
  32771. * The material `id` is a string identifying the material or the multiMaterial.
  32772. * This method returns the Mesh.
  32773. */
  32774. Mesh.prototype.setMaterialByID = function (id) {
  32775. var materials = this.getScene().materials;
  32776. var index;
  32777. for (index = materials.length - 1; index > -1; index--) {
  32778. if (materials[index].id === id) {
  32779. this.material = materials[index];
  32780. return this;
  32781. }
  32782. }
  32783. // Multi
  32784. var multiMaterials = this.getScene().multiMaterials;
  32785. for (index = multiMaterials.length - 1; index > -1; index--) {
  32786. if (multiMaterials[index].id === id) {
  32787. this.material = multiMaterials[index];
  32788. return this;
  32789. }
  32790. }
  32791. return this;
  32792. };
  32793. /**
  32794. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32795. */
  32796. Mesh.prototype.getAnimatables = function () {
  32797. var results = new Array();
  32798. if (this.material) {
  32799. results.push(this.material);
  32800. }
  32801. if (this.skeleton) {
  32802. results.push(this.skeleton);
  32803. }
  32804. return results;
  32805. };
  32806. /**
  32807. * Modifies the mesh geometry according to the passed transformation matrix.
  32808. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32809. * The mesh normals are modified accordingly the same transformation.
  32810. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32811. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32812. * Returns the Mesh.
  32813. */
  32814. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32815. // Position
  32816. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32817. return this;
  32818. }
  32819. var submeshes = this.subMeshes.splice(0);
  32820. this._resetPointsArrayCache();
  32821. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32822. var temp = new Array();
  32823. var index;
  32824. for (index = 0; index < data.length; index += 3) {
  32825. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32826. }
  32827. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32828. // Normals
  32829. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32830. return this;
  32831. }
  32832. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32833. temp = [];
  32834. for (index = 0; index < data.length; index += 3) {
  32835. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32836. }
  32837. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32838. // flip faces?
  32839. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32840. this.flipFaces();
  32841. }
  32842. // Restore submeshes
  32843. this.releaseSubMeshes();
  32844. this.subMeshes = submeshes;
  32845. return this;
  32846. };
  32847. /**
  32848. * Modifies the mesh geometry according to its own current World Matrix.
  32849. * The mesh World Matrix is then reset.
  32850. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32851. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32852. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32853. * Returns the Mesh.
  32854. */
  32855. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32856. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32857. this.scaling.copyFromFloats(1, 1, 1);
  32858. this.position.copyFromFloats(0, 0, 0);
  32859. this.rotation.copyFromFloats(0, 0, 0);
  32860. //only if quaternion is already set
  32861. if (this.rotationQuaternion) {
  32862. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32863. }
  32864. this._worldMatrix = BABYLON.Matrix.Identity();
  32865. return this;
  32866. };
  32867. Object.defineProperty(Mesh.prototype, "_positions", {
  32868. // Cache
  32869. get: function () {
  32870. if (this._geometry) {
  32871. return this._geometry._positions;
  32872. }
  32873. return null;
  32874. },
  32875. enumerable: true,
  32876. configurable: true
  32877. });
  32878. Mesh.prototype._resetPointsArrayCache = function () {
  32879. if (this._geometry) {
  32880. this._geometry._resetPointsArrayCache();
  32881. }
  32882. return this;
  32883. };
  32884. Mesh.prototype._generatePointsArray = function () {
  32885. if (this._geometry) {
  32886. return this._geometry._generatePointsArray();
  32887. }
  32888. return false;
  32889. };
  32890. /**
  32891. * Returns a new Mesh object generated from the current mesh properties.
  32892. * This method must not get confused with createInstance().
  32893. * The parameter `name` is a string, the name given to the new mesh.
  32894. * The optional parameter `newParent` can be any Node object (default `null`).
  32895. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32896. * 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.
  32897. */
  32898. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32899. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32900. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32901. };
  32902. /**
  32903. * Releases resources associated with this mesh.
  32904. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32905. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32906. */
  32907. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32908. var _this = this;
  32909. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32910. this.morphTargetManager = null;
  32911. if (this._geometry) {
  32912. this._geometry.releaseForMesh(this, true);
  32913. }
  32914. // Sources
  32915. var meshes = this.getScene().meshes;
  32916. meshes.forEach(function (abstractMesh) {
  32917. var mesh = abstractMesh;
  32918. if (mesh._source && mesh._source === _this) {
  32919. mesh._source = null;
  32920. }
  32921. });
  32922. this._source = null;
  32923. // Instances
  32924. if (this._instancesBuffer) {
  32925. this._instancesBuffer.dispose();
  32926. this._instancesBuffer = null;
  32927. }
  32928. while (this.instances.length) {
  32929. this.instances[0].dispose();
  32930. }
  32931. // Effect layers.
  32932. var effectLayers = this.getScene().effectLayers;
  32933. for (var i = 0; i < effectLayers.length; i++) {
  32934. var effectLayer = effectLayers[i];
  32935. if (effectLayer) {
  32936. effectLayer._disposeMesh(this);
  32937. }
  32938. }
  32939. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32940. };
  32941. /**
  32942. * Modifies the mesh geometry according to a displacement map.
  32943. * 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.
  32944. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32945. * This method returns nothing.
  32946. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32947. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32948. * 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.
  32949. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32950. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32951. *
  32952. * Returns the Mesh.
  32953. */
  32954. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32955. var _this = this;
  32956. var scene = this.getScene();
  32957. var onload = function (img) {
  32958. // Getting height map data
  32959. var canvas = document.createElement("canvas");
  32960. var context = canvas.getContext("2d");
  32961. var heightMapWidth = img.width;
  32962. var heightMapHeight = img.height;
  32963. canvas.width = heightMapWidth;
  32964. canvas.height = heightMapHeight;
  32965. context.drawImage(img, 0, 0);
  32966. // Create VertexData from map data
  32967. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32968. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32969. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32970. //execute success callback, if set
  32971. if (onSuccess) {
  32972. onSuccess(_this);
  32973. }
  32974. };
  32975. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32976. return this;
  32977. };
  32978. /**
  32979. * Modifies the mesh geometry according to a displacementMap buffer.
  32980. * 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.
  32981. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32982. * This method returns nothing.
  32983. * 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.
  32984. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32985. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32986. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32987. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32988. *
  32989. * Returns the Mesh.
  32990. */
  32991. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32992. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32993. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32994. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32995. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32996. return this;
  32997. }
  32998. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32999. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33000. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33001. var position = BABYLON.Vector3.Zero();
  33002. var normal = BABYLON.Vector3.Zero();
  33003. var uv = BABYLON.Vector2.Zero();
  33004. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  33005. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  33006. for (var index = 0; index < positions.length; index += 3) {
  33007. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  33008. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  33009. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  33010. // Compute height
  33011. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  33012. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  33013. var pos = (u + v * heightMapWidth) * 4;
  33014. var r = buffer[pos] / 255.0;
  33015. var g = buffer[pos + 1] / 255.0;
  33016. var b = buffer[pos + 2] / 255.0;
  33017. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33018. normal.normalize();
  33019. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  33020. position = position.add(normal);
  33021. position.toArray(positions, index);
  33022. }
  33023. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  33024. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33025. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33026. return this;
  33027. };
  33028. /**
  33029. * Modify the mesh to get a flat shading rendering.
  33030. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  33031. * This method returns the Mesh.
  33032. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  33033. */
  33034. Mesh.prototype.convertToFlatShadedMesh = function () {
  33035. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  33036. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33037. var kinds = this.getVerticesDataKinds();
  33038. var vbs = {};
  33039. var data = {};
  33040. var newdata = {};
  33041. var updatableNormals = false;
  33042. var kindIndex;
  33043. var kind;
  33044. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33045. kind = kinds[kindIndex];
  33046. var vertexBuffer = this.getVertexBuffer(kind);
  33047. if (kind === BABYLON.VertexBuffer.NormalKind) {
  33048. updatableNormals = vertexBuffer.isUpdatable();
  33049. kinds.splice(kindIndex, 1);
  33050. kindIndex--;
  33051. continue;
  33052. }
  33053. vbs[kind] = vertexBuffer;
  33054. data[kind] = vbs[kind].getData();
  33055. newdata[kind] = [];
  33056. }
  33057. // Save previous submeshes
  33058. var previousSubmeshes = this.subMeshes.slice(0);
  33059. var indices = this.getIndices();
  33060. var totalIndices = this.getTotalIndices();
  33061. // Generating unique vertices per face
  33062. var index;
  33063. for (index = 0; index < totalIndices; index++) {
  33064. var vertexIndex = indices[index];
  33065. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33066. kind = kinds[kindIndex];
  33067. var stride = vbs[kind].getStrideSize();
  33068. for (var offset = 0; offset < stride; offset++) {
  33069. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33070. }
  33071. }
  33072. }
  33073. // Updating faces & normal
  33074. var normals = [];
  33075. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33076. for (index = 0; index < totalIndices; index += 3) {
  33077. indices[index] = index;
  33078. indices[index + 1] = index + 1;
  33079. indices[index + 2] = index + 2;
  33080. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33081. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33082. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33083. var p1p2 = p1.subtract(p2);
  33084. var p3p2 = p3.subtract(p2);
  33085. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33086. // Store same normals for every vertex
  33087. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33088. normals.push(normal.x);
  33089. normals.push(normal.y);
  33090. normals.push(normal.z);
  33091. }
  33092. }
  33093. this.setIndices(indices);
  33094. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33095. // Updating vertex buffers
  33096. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33097. kind = kinds[kindIndex];
  33098. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33099. }
  33100. // Updating submeshes
  33101. this.releaseSubMeshes();
  33102. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33103. var previousOne = previousSubmeshes[submeshIndex];
  33104. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33105. }
  33106. this.synchronizeInstances();
  33107. return this;
  33108. };
  33109. /**
  33110. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33111. * In other words, more vertices, no more indices and a single bigger VBO.
  33112. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33113. * Returns the Mesh.
  33114. */
  33115. Mesh.prototype.convertToUnIndexedMesh = function () {
  33116. /// <summary>Remove indices by unfolding faces into buffers</summary>
  33117. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33118. var kinds = this.getVerticesDataKinds();
  33119. var vbs = {};
  33120. var data = {};
  33121. var newdata = {};
  33122. var kindIndex;
  33123. var kind;
  33124. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33125. kind = kinds[kindIndex];
  33126. var vertexBuffer = this.getVertexBuffer(kind);
  33127. vbs[kind] = vertexBuffer;
  33128. data[kind] = vbs[kind].getData();
  33129. newdata[kind] = [];
  33130. }
  33131. // Save previous submeshes
  33132. var previousSubmeshes = this.subMeshes.slice(0);
  33133. var indices = this.getIndices();
  33134. var totalIndices = this.getTotalIndices();
  33135. // Generating unique vertices per face
  33136. var index;
  33137. for (index = 0; index < totalIndices; index++) {
  33138. var vertexIndex = indices[index];
  33139. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33140. kind = kinds[kindIndex];
  33141. var stride = vbs[kind].getStrideSize();
  33142. for (var offset = 0; offset < stride; offset++) {
  33143. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33144. }
  33145. }
  33146. }
  33147. // Updating indices
  33148. for (index = 0; index < totalIndices; index += 3) {
  33149. indices[index] = index;
  33150. indices[index + 1] = index + 1;
  33151. indices[index + 2] = index + 2;
  33152. }
  33153. this.setIndices(indices);
  33154. // Updating vertex buffers
  33155. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33156. kind = kinds[kindIndex];
  33157. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33158. }
  33159. // Updating submeshes
  33160. this.releaseSubMeshes();
  33161. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33162. var previousOne = previousSubmeshes[submeshIndex];
  33163. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33164. }
  33165. this._unIndexed = true;
  33166. this.synchronizeInstances();
  33167. return this;
  33168. };
  33169. /**
  33170. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33171. * This method returns the Mesh.
  33172. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33173. */
  33174. Mesh.prototype.flipFaces = function (flipNormals) {
  33175. if (flipNormals === void 0) { flipNormals = false; }
  33176. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33177. var i;
  33178. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33179. for (i = 0; i < vertex_data.normals.length; i++) {
  33180. vertex_data.normals[i] *= -1;
  33181. }
  33182. }
  33183. if (vertex_data.indices) {
  33184. var temp;
  33185. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33186. // reassign indices
  33187. temp = vertex_data.indices[i + 1];
  33188. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33189. vertex_data.indices[i + 2] = temp;
  33190. }
  33191. }
  33192. vertex_data.applyToMesh(this);
  33193. return this;
  33194. };
  33195. // Instances
  33196. /**
  33197. * Creates a new InstancedMesh object from the mesh model.
  33198. * An instance shares the same properties and the same material than its model.
  33199. * Only these properties of each instance can then be set individually :
  33200. * - position
  33201. * - rotation
  33202. * - rotationQuaternion
  33203. * - setPivotMatrix
  33204. * - scaling
  33205. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  33206. * Warning : this method is not supported for Line mesh and LineSystem
  33207. */
  33208. Mesh.prototype.createInstance = function (name) {
  33209. return new BABYLON.InstancedMesh(name, this);
  33210. };
  33211. /**
  33212. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33213. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33214. * This method returns the Mesh.
  33215. */
  33216. Mesh.prototype.synchronizeInstances = function () {
  33217. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33218. var instance = this.instances[instanceIndex];
  33219. instance._syncSubMeshes();
  33220. }
  33221. return this;
  33222. };
  33223. /**
  33224. * Simplify the mesh according to the given array of settings.
  33225. * Function will return immediately and will simplify async. It returns the Mesh.
  33226. * @param settings a collection of simplification settings.
  33227. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33228. * @param type the type of simplification to run.
  33229. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33230. */
  33231. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33232. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33233. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33234. this.getScene().simplificationQueue.addTask({
  33235. settings: settings,
  33236. parallelProcessing: parallelProcessing,
  33237. mesh: this,
  33238. simplificationType: simplificationType,
  33239. successCallback: successCallback
  33240. });
  33241. return this;
  33242. };
  33243. /**
  33244. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33245. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33246. * This should be used together with the simplification to avoid disappearing triangles.
  33247. * Returns the Mesh.
  33248. * @param successCallback an optional success callback to be called after the optimization finished.
  33249. */
  33250. Mesh.prototype.optimizeIndices = function (successCallback) {
  33251. var _this = this;
  33252. var indices = this.getIndices();
  33253. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33254. if (!positions || !indices) {
  33255. return this;
  33256. }
  33257. var vectorPositions = new Array();
  33258. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33259. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33260. }
  33261. var dupes = new Array();
  33262. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33263. var realPos = vectorPositions.length - 1 - iteration;
  33264. var testedPosition = vectorPositions[realPos];
  33265. for (var j = 0; j < realPos; ++j) {
  33266. var againstPosition = vectorPositions[j];
  33267. if (testedPosition.equals(againstPosition)) {
  33268. dupes[realPos] = j;
  33269. break;
  33270. }
  33271. }
  33272. }, function () {
  33273. for (var i = 0; i < indices.length; ++i) {
  33274. indices[i] = dupes[indices[i]] || indices[i];
  33275. }
  33276. //indices are now reordered
  33277. var originalSubMeshes = _this.subMeshes.slice(0);
  33278. _this.setIndices(indices);
  33279. _this.subMeshes = originalSubMeshes;
  33280. if (successCallback) {
  33281. successCallback(_this);
  33282. }
  33283. });
  33284. return this;
  33285. };
  33286. Mesh.prototype.serialize = function (serializationObject) {
  33287. serializationObject.name = this.name;
  33288. serializationObject.id = this.id;
  33289. serializationObject.type = this.getClassName();
  33290. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33291. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33292. }
  33293. serializationObject.position = this.position.asArray();
  33294. if (this.rotationQuaternion) {
  33295. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33296. }
  33297. else if (this.rotation) {
  33298. serializationObject.rotation = this.rotation.asArray();
  33299. }
  33300. serializationObject.scaling = this.scaling.asArray();
  33301. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33302. serializationObject.isEnabled = this.isEnabled(false);
  33303. serializationObject.isVisible = this.isVisible;
  33304. serializationObject.infiniteDistance = this.infiniteDistance;
  33305. serializationObject.pickable = this.isPickable;
  33306. serializationObject.receiveShadows = this.receiveShadows;
  33307. serializationObject.billboardMode = this.billboardMode;
  33308. serializationObject.visibility = this.visibility;
  33309. serializationObject.checkCollisions = this.checkCollisions;
  33310. serializationObject.isBlocker = this.isBlocker;
  33311. // Parent
  33312. if (this.parent) {
  33313. serializationObject.parentId = this.parent.id;
  33314. }
  33315. // Geometry
  33316. serializationObject.isUnIndexed = this.isUnIndexed;
  33317. var geometry = this._geometry;
  33318. if (geometry) {
  33319. var geometryId = geometry.id;
  33320. serializationObject.geometryId = geometryId;
  33321. // SubMeshes
  33322. serializationObject.subMeshes = [];
  33323. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33324. var subMesh = this.subMeshes[subIndex];
  33325. serializationObject.subMeshes.push({
  33326. materialIndex: subMesh.materialIndex,
  33327. verticesStart: subMesh.verticesStart,
  33328. verticesCount: subMesh.verticesCount,
  33329. indexStart: subMesh.indexStart,
  33330. indexCount: subMesh.indexCount
  33331. });
  33332. }
  33333. }
  33334. // Material
  33335. if (this.material) {
  33336. serializationObject.materialId = this.material.id;
  33337. }
  33338. else {
  33339. this.material = null;
  33340. }
  33341. // Morph targets
  33342. if (this.morphTargetManager) {
  33343. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33344. }
  33345. // Skeleton
  33346. if (this.skeleton) {
  33347. serializationObject.skeletonId = this.skeleton.id;
  33348. }
  33349. // Physics
  33350. //TODO implement correct serialization for physics impostors.
  33351. var impostor = this.getPhysicsImpostor();
  33352. if (impostor) {
  33353. serializationObject.physicsMass = impostor.getParam("mass");
  33354. serializationObject.physicsFriction = impostor.getParam("friction");
  33355. serializationObject.physicsRestitution = impostor.getParam("mass");
  33356. serializationObject.physicsImpostor = impostor.type;
  33357. }
  33358. // Metadata
  33359. if (this.metadata) {
  33360. serializationObject.metadata = this.metadata;
  33361. }
  33362. // Instances
  33363. serializationObject.instances = [];
  33364. for (var index = 0; index < this.instances.length; index++) {
  33365. var instance = this.instances[index];
  33366. var serializationInstance = {
  33367. name: instance.name,
  33368. id: instance.id,
  33369. position: instance.position.asArray(),
  33370. scaling: instance.scaling.asArray()
  33371. };
  33372. if (instance.rotationQuaternion) {
  33373. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33374. }
  33375. else if (instance.rotation) {
  33376. serializationInstance.rotation = instance.rotation.asArray();
  33377. }
  33378. serializationObject.instances.push(serializationInstance);
  33379. // Animations
  33380. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33381. serializationInstance.ranges = instance.serializeAnimationRanges();
  33382. }
  33383. //
  33384. // Animations
  33385. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33386. serializationObject.ranges = this.serializeAnimationRanges();
  33387. // Layer mask
  33388. serializationObject.layerMask = this.layerMask;
  33389. // Alpha
  33390. serializationObject.alphaIndex = this.alphaIndex;
  33391. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33392. // Overlay
  33393. serializationObject.overlayAlpha = this.overlayAlpha;
  33394. serializationObject.overlayColor = this.overlayColor.asArray();
  33395. serializationObject.renderOverlay = this.renderOverlay;
  33396. // Fog
  33397. serializationObject.applyFog = this.applyFog;
  33398. // Action Manager
  33399. if (this.actionManager) {
  33400. serializationObject.actions = this.actionManager.serialize(this.name);
  33401. }
  33402. };
  33403. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33404. if (!this.geometry) {
  33405. return;
  33406. }
  33407. this._markSubMeshesAsAttributesDirty();
  33408. var morphTargetManager = this._morphTargetManager;
  33409. if (morphTargetManager && morphTargetManager.vertexCount) {
  33410. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33411. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33412. this.morphTargetManager = null;
  33413. return;
  33414. }
  33415. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33416. var morphTarget = morphTargetManager.getActiveTarget(index);
  33417. var positions = morphTarget.getPositions();
  33418. if (!positions) {
  33419. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33420. return;
  33421. }
  33422. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33423. var normals = morphTarget.getNormals();
  33424. if (normals) {
  33425. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33426. }
  33427. var tangents = morphTarget.getTangents();
  33428. if (tangents) {
  33429. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33430. }
  33431. }
  33432. }
  33433. else {
  33434. var index = 0;
  33435. // Positions
  33436. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33437. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33438. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33439. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33440. }
  33441. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33442. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33443. }
  33444. index++;
  33445. }
  33446. }
  33447. };
  33448. // Statics
  33449. /**
  33450. * Returns a new Mesh object parsed from the source provided.
  33451. * The parameter `parsedMesh` is the source.
  33452. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33453. */
  33454. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33455. var mesh;
  33456. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33457. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33458. }
  33459. else {
  33460. mesh = new Mesh(parsedMesh.name, scene);
  33461. }
  33462. mesh.id = parsedMesh.id;
  33463. if (BABYLON.Tags) {
  33464. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33465. }
  33466. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33467. if (parsedMesh.metadata !== undefined) {
  33468. mesh.metadata = parsedMesh.metadata;
  33469. }
  33470. if (parsedMesh.rotationQuaternion) {
  33471. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33472. }
  33473. else if (parsedMesh.rotation) {
  33474. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33475. }
  33476. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33477. if (parsedMesh.localMatrix) {
  33478. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33479. }
  33480. else if (parsedMesh.pivotMatrix) {
  33481. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33482. }
  33483. mesh.setEnabled(parsedMesh.isEnabled);
  33484. mesh.isVisible = parsedMesh.isVisible;
  33485. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33486. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33487. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33488. if (parsedMesh.applyFog !== undefined) {
  33489. mesh.applyFog = parsedMesh.applyFog;
  33490. }
  33491. if (parsedMesh.pickable !== undefined) {
  33492. mesh.isPickable = parsedMesh.pickable;
  33493. }
  33494. if (parsedMesh.alphaIndex !== undefined) {
  33495. mesh.alphaIndex = parsedMesh.alphaIndex;
  33496. }
  33497. mesh.receiveShadows = parsedMesh.receiveShadows;
  33498. mesh.billboardMode = parsedMesh.billboardMode;
  33499. if (parsedMesh.visibility !== undefined) {
  33500. mesh.visibility = parsedMesh.visibility;
  33501. }
  33502. mesh.checkCollisions = parsedMesh.checkCollisions;
  33503. if (parsedMesh.isBlocker !== undefined) {
  33504. mesh.isBlocker = parsedMesh.isBlocker;
  33505. }
  33506. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33507. // freezeWorldMatrix
  33508. if (parsedMesh.freezeWorldMatrix) {
  33509. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33510. }
  33511. // Parent
  33512. if (parsedMesh.parentId) {
  33513. mesh._waitingParentId = parsedMesh.parentId;
  33514. }
  33515. // Actions
  33516. if (parsedMesh.actions !== undefined) {
  33517. mesh._waitingActions = parsedMesh.actions;
  33518. }
  33519. // Overlay
  33520. if (parsedMesh.overlayAlpha !== undefined) {
  33521. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33522. }
  33523. if (parsedMesh.overlayColor !== undefined) {
  33524. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33525. }
  33526. if (parsedMesh.renderOverlay !== undefined) {
  33527. mesh.renderOverlay = parsedMesh.renderOverlay;
  33528. }
  33529. // Geometry
  33530. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33531. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33532. if (parsedMesh.delayLoadingFile) {
  33533. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33534. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33535. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33536. if (parsedMesh._binaryInfo) {
  33537. mesh._binaryInfo = parsedMesh._binaryInfo;
  33538. }
  33539. mesh._delayInfo = [];
  33540. if (parsedMesh.hasUVs) {
  33541. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33542. }
  33543. if (parsedMesh.hasUVs2) {
  33544. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33545. }
  33546. if (parsedMesh.hasUVs3) {
  33547. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33548. }
  33549. if (parsedMesh.hasUVs4) {
  33550. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33551. }
  33552. if (parsedMesh.hasUVs5) {
  33553. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33554. }
  33555. if (parsedMesh.hasUVs6) {
  33556. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33557. }
  33558. if (parsedMesh.hasColors) {
  33559. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33560. }
  33561. if (parsedMesh.hasMatricesIndices) {
  33562. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33563. }
  33564. if (parsedMesh.hasMatricesWeights) {
  33565. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33566. }
  33567. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33568. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33569. mesh._checkDelayState();
  33570. }
  33571. }
  33572. else {
  33573. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33574. }
  33575. // Material
  33576. if (parsedMesh.materialId) {
  33577. mesh.setMaterialByID(parsedMesh.materialId);
  33578. }
  33579. else {
  33580. mesh.material = null;
  33581. }
  33582. // Morph targets
  33583. if (parsedMesh.morphTargetManagerId > -1) {
  33584. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33585. }
  33586. // Skeleton
  33587. if (parsedMesh.skeletonId > -1) {
  33588. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33589. if (parsedMesh.numBoneInfluencers) {
  33590. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33591. }
  33592. }
  33593. // Animations
  33594. if (parsedMesh.animations) {
  33595. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33596. var parsedAnimation = parsedMesh.animations[animationIndex];
  33597. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33598. }
  33599. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33600. }
  33601. if (parsedMesh.autoAnimate) {
  33602. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33603. }
  33604. // Layer Mask
  33605. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33606. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33607. }
  33608. else {
  33609. mesh.layerMask = 0x0FFFFFFF;
  33610. }
  33611. // Physics
  33612. if (parsedMesh.physicsImpostor) {
  33613. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33614. mass: parsedMesh.physicsMass,
  33615. friction: parsedMesh.physicsFriction,
  33616. restitution: parsedMesh.physicsRestitution
  33617. }, scene);
  33618. }
  33619. // Instances
  33620. if (parsedMesh.instances) {
  33621. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33622. var parsedInstance = parsedMesh.instances[index];
  33623. var instance = mesh.createInstance(parsedInstance.name);
  33624. if (parsedInstance.id) {
  33625. instance.id = parsedInstance.id;
  33626. }
  33627. if (BABYLON.Tags) {
  33628. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33629. }
  33630. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33631. if (parsedInstance.parentId) {
  33632. instance._waitingParentId = parsedInstance.parentId;
  33633. }
  33634. if (parsedInstance.rotationQuaternion) {
  33635. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33636. }
  33637. else if (parsedInstance.rotation) {
  33638. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33639. }
  33640. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33641. instance.checkCollisions = mesh.checkCollisions;
  33642. if (parsedMesh.animations) {
  33643. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33644. parsedAnimation = parsedMesh.animations[animationIndex];
  33645. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33646. }
  33647. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33648. if (parsedMesh.autoAnimate) {
  33649. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33650. }
  33651. }
  33652. }
  33653. }
  33654. return mesh;
  33655. };
  33656. /**
  33657. * Creates a ribbon mesh.
  33658. * Please consider using the same method from the MeshBuilder class instead.
  33659. * 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.
  33660. *
  33661. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33662. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33663. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33664. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33665. * 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.
  33666. * 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.
  33667. * 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
  33668. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33669. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33670. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33671. */
  33672. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33673. if (closeArray === void 0) { closeArray = false; }
  33674. if (updatable === void 0) { updatable = false; }
  33675. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33676. pathArray: pathArray,
  33677. closeArray: closeArray,
  33678. closePath: closePath,
  33679. offset: offset,
  33680. updatable: updatable,
  33681. sideOrientation: sideOrientation,
  33682. instance: instance
  33683. }, scene);
  33684. };
  33685. /**
  33686. * Creates a plane polygonal mesh. By default, this is a disc.
  33687. * Please consider using the same method from the MeshBuilder class instead.
  33688. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33689. * 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.
  33690. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33691. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33692. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33693. */
  33694. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33695. if (scene === void 0) { scene = null; }
  33696. var options = {
  33697. radius: radius,
  33698. tessellation: tessellation,
  33699. sideOrientation: sideOrientation,
  33700. updatable: updatable
  33701. };
  33702. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33703. };
  33704. /**
  33705. * Creates a box mesh.
  33706. * Please consider using the same method from the MeshBuilder class instead.
  33707. * The parameter `size` sets the size (float) of each box side (default 1).
  33708. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33709. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33710. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33711. */
  33712. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33713. if (scene === void 0) { scene = null; }
  33714. var options = {
  33715. size: size,
  33716. sideOrientation: sideOrientation,
  33717. updatable: updatable
  33718. };
  33719. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33720. };
  33721. /**
  33722. * Creates a sphere mesh.
  33723. * Please consider using the same method from the MeshBuilder class instead.
  33724. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33725. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33726. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33727. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33728. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33729. */
  33730. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33731. var options = {
  33732. segments: segments,
  33733. diameterX: diameter,
  33734. diameterY: diameter,
  33735. diameterZ: diameter,
  33736. sideOrientation: sideOrientation,
  33737. updatable: updatable
  33738. };
  33739. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33740. };
  33741. /**
  33742. * Creates a cylinder or a cone mesh.
  33743. * Please consider using the same method from the MeshBuilder class instead.
  33744. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33745. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33746. * 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.
  33747. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33748. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33749. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33750. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33751. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33752. */
  33753. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33754. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33755. if (scene !== undefined) {
  33756. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33757. updatable = scene;
  33758. }
  33759. scene = subdivisions;
  33760. subdivisions = 1;
  33761. }
  33762. var options = {
  33763. height: height,
  33764. diameterTop: diameterTop,
  33765. diameterBottom: diameterBottom,
  33766. tessellation: tessellation,
  33767. subdivisions: subdivisions,
  33768. sideOrientation: sideOrientation,
  33769. updatable: updatable
  33770. };
  33771. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33772. };
  33773. // Torus (Code from SharpDX.org)
  33774. /**
  33775. * Creates a torus mesh.
  33776. * Please consider using the same method from the MeshBuilder class instead.
  33777. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33778. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33779. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33780. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33781. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33782. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33783. */
  33784. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33785. var options = {
  33786. diameter: diameter,
  33787. thickness: thickness,
  33788. tessellation: tessellation,
  33789. sideOrientation: sideOrientation,
  33790. updatable: updatable
  33791. };
  33792. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33793. };
  33794. /**
  33795. * Creates a torus knot mesh.
  33796. * Please consider using the same method from the MeshBuilder class instead.
  33797. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33798. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33799. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33800. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33801. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33802. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33803. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33804. */
  33805. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33806. var options = {
  33807. radius: radius,
  33808. tube: tube,
  33809. radialSegments: radialSegments,
  33810. tubularSegments: tubularSegments,
  33811. p: p,
  33812. q: q,
  33813. sideOrientation: sideOrientation,
  33814. updatable: updatable
  33815. };
  33816. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33817. };
  33818. /**
  33819. * Creates a line mesh.
  33820. * Please consider using the same method from the MeshBuilder class instead.
  33821. * 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.
  33822. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33823. * The parameter `points` is an array successive Vector3.
  33824. * 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
  33825. * When updating an instance, remember that only point positions can change, not the number of points.
  33826. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33827. */
  33828. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33829. if (scene === void 0) { scene = null; }
  33830. if (updatable === void 0) { updatable = false; }
  33831. if (instance === void 0) { instance = null; }
  33832. var options = {
  33833. points: points,
  33834. updatable: updatable,
  33835. instance: instance
  33836. };
  33837. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33838. };
  33839. /**
  33840. * Creates a dashed line mesh.
  33841. * Please consider using the same method from the MeshBuilder class instead.
  33842. * 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.
  33843. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33844. * The parameter `points` is an array successive Vector3.
  33845. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33846. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33847. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33848. * 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
  33849. * When updating an instance, remember that only point positions can change, not the number of points.
  33850. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33851. */
  33852. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33853. if (scene === void 0) { scene = null; }
  33854. var options = {
  33855. points: points,
  33856. dashSize: dashSize,
  33857. gapSize: gapSize,
  33858. dashNb: dashNb,
  33859. updatable: updatable,
  33860. instance: instance
  33861. };
  33862. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33863. };
  33864. /**
  33865. * Creates a polygon mesh.
  33866. * Please consider using the same method from the MeshBuilder class instead.
  33867. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33868. * 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.
  33869. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33870. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33871. * Remember you can only change the shape positions, not their number when updating a polygon.
  33872. */
  33873. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33874. var options = {
  33875. shape: shape,
  33876. holes: holes,
  33877. updatable: updatable,
  33878. sideOrientation: sideOrientation
  33879. };
  33880. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33881. };
  33882. /**
  33883. * Creates an extruded polygon mesh, with depth in the Y direction.
  33884. * Please consider using the same method from the MeshBuilder class instead.
  33885. */
  33886. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33887. var options = {
  33888. shape: shape,
  33889. holes: holes,
  33890. depth: depth,
  33891. updatable: updatable,
  33892. sideOrientation: sideOrientation
  33893. };
  33894. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33895. };
  33896. /**
  33897. * Creates an extruded shape mesh.
  33898. * 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.
  33899. * Please consider using the same method from the MeshBuilder class instead.
  33900. *
  33901. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33902. * 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
  33903. * extruded along the Z axis.
  33904. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33905. * 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.
  33906. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33907. * 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
  33908. * 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
  33909. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33910. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33911. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33912. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33913. */
  33914. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33915. if (scene === void 0) { scene = null; }
  33916. var options = {
  33917. shape: shape,
  33918. path: path,
  33919. scale: scale,
  33920. rotation: rotation,
  33921. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33922. sideOrientation: sideOrientation,
  33923. instance: instance,
  33924. updatable: updatable
  33925. };
  33926. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33927. };
  33928. /**
  33929. * Creates an custom extruded shape mesh.
  33930. * 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.
  33931. * Please consider using the same method from the MeshBuilder class instead.
  33932. *
  33933. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33934. * 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
  33935. * extruded along the Z axis.
  33936. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33937. * 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
  33938. * and the distance of this point from the begining of the path :
  33939. * ```javascript
  33940. * var rotationFunction = function(i, distance) {
  33941. * // do things
  33942. * return rotationValue; }
  33943. * ```
  33944. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33945. * 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
  33946. * and the distance of this point from the begining of the path :
  33947. * ```javascript
  33948. * var scaleFunction = function(i, distance) {
  33949. * // do things
  33950. * return scaleValue;}
  33951. * ```
  33952. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33953. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33954. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33955. * 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
  33956. * 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
  33957. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33958. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33959. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33960. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33961. */
  33962. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33963. var options = {
  33964. shape: shape,
  33965. path: path,
  33966. scaleFunction: scaleFunction,
  33967. rotationFunction: rotationFunction,
  33968. ribbonCloseArray: ribbonCloseArray,
  33969. ribbonClosePath: ribbonClosePath,
  33970. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33971. sideOrientation: sideOrientation,
  33972. instance: instance,
  33973. updatable: updatable
  33974. };
  33975. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33976. };
  33977. /**
  33978. * Creates lathe mesh.
  33979. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33980. * Please consider using the same method from the MeshBuilder class instead.
  33981. * 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
  33982. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33983. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33984. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33985. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33986. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33987. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33988. */
  33989. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33990. var options = {
  33991. shape: shape,
  33992. radius: radius,
  33993. tessellation: tessellation,
  33994. sideOrientation: sideOrientation,
  33995. updatable: updatable
  33996. };
  33997. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33998. };
  33999. /**
  34000. * Creates a plane mesh.
  34001. * Please consider using the same method from the MeshBuilder class instead.
  34002. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  34003. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34004. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34005. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34006. */
  34007. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  34008. var options = {
  34009. size: size,
  34010. width: size,
  34011. height: size,
  34012. sideOrientation: sideOrientation,
  34013. updatable: updatable
  34014. };
  34015. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  34016. };
  34017. /**
  34018. * Creates a ground mesh.
  34019. * Please consider using the same method from the MeshBuilder class instead.
  34020. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  34021. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  34022. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34023. */
  34024. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  34025. var options = {
  34026. width: width,
  34027. height: height,
  34028. subdivisions: subdivisions,
  34029. updatable: updatable
  34030. };
  34031. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  34032. };
  34033. /**
  34034. * Creates a tiled ground mesh.
  34035. * Please consider using the same method from the MeshBuilder class instead.
  34036. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  34037. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  34038. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  34039. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  34040. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  34041. * numbers of subdivisions on the ground width and height of each tile.
  34042. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34043. */
  34044. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  34045. var options = {
  34046. xmin: xmin,
  34047. zmin: zmin,
  34048. xmax: xmax,
  34049. zmax: zmax,
  34050. subdivisions: subdivisions,
  34051. precision: precision,
  34052. updatable: updatable
  34053. };
  34054. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  34055. };
  34056. /**
  34057. * Creates a ground mesh from a height map.
  34058. * tuto : http://doc.babylonjs.com/babylon101/height_map
  34059. * Please consider using the same method from the MeshBuilder class instead.
  34060. * The parameter `url` sets the URL of the height map image resource.
  34061. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  34062. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  34063. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  34064. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  34065. * 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).
  34066. * This function is passed the newly built mesh :
  34067. * ```javascript
  34068. * function(mesh) { // do things
  34069. * return; }
  34070. * ```
  34071. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34072. */
  34073. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  34074. var options = {
  34075. width: width,
  34076. height: height,
  34077. subdivisions: subdivisions,
  34078. minHeight: minHeight,
  34079. maxHeight: maxHeight,
  34080. updatable: updatable,
  34081. onReady: onReady
  34082. };
  34083. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34084. };
  34085. /**
  34086. * Creates a tube mesh.
  34087. * 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.
  34088. * Please consider using the same method from the MeshBuilder class instead.
  34089. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  34090. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  34091. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  34092. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  34093. * 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.
  34094. * It must return a radius value (positive float) :
  34095. * ```javascript
  34096. * var radiusFunction = function(i, distance) {
  34097. * // do things
  34098. * return radius; }
  34099. * ```
  34100. * 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
  34101. * 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
  34102. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34103. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34104. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34105. */
  34106. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34107. var options = {
  34108. path: path,
  34109. radius: radius,
  34110. tessellation: tessellation,
  34111. radiusFunction: radiusFunction,
  34112. arc: 1,
  34113. cap: cap,
  34114. updatable: updatable,
  34115. sideOrientation: sideOrientation,
  34116. instance: instance
  34117. };
  34118. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34119. };
  34120. /**
  34121. * Creates a polyhedron mesh.
  34122. * Please consider using the same method from the MeshBuilder class instead.
  34123. * 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
  34124. * to choose the wanted type.
  34125. * The parameter `size` (positive float, default 1) sets the polygon size.
  34126. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  34127. * 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`.
  34128. * 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
  34129. * 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)`).
  34130. * 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
  34131. * 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.
  34132. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34133. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34134. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34135. */
  34136. Mesh.CreatePolyhedron = function (name, options, scene) {
  34137. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34138. };
  34139. /**
  34140. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  34141. * Please consider using the same method from the MeshBuilder class instead.
  34142. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  34143. * 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`).
  34144. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  34145. * 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.
  34146. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34147. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34148. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34149. */
  34150. Mesh.CreateIcoSphere = function (name, options, scene) {
  34151. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34152. };
  34153. /**
  34154. * Creates a decal mesh.
  34155. * Please consider using the same method from the MeshBuilder class instead.
  34156. * 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.
  34157. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34158. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34159. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34160. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34161. */
  34162. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34163. var options = {
  34164. position: position,
  34165. normal: normal,
  34166. size: size,
  34167. angle: angle
  34168. };
  34169. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34170. };
  34171. // Skeletons
  34172. /**
  34173. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34174. */
  34175. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34176. if (!this._sourcePositions) {
  34177. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34178. if (!source) {
  34179. return this._sourcePositions;
  34180. }
  34181. this._sourcePositions = new Float32Array(source);
  34182. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34183. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34184. }
  34185. }
  34186. return this._sourcePositions;
  34187. };
  34188. /**
  34189. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34190. */
  34191. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34192. if (!this._sourceNormals) {
  34193. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34194. if (!source) {
  34195. return this._sourceNormals;
  34196. }
  34197. this._sourceNormals = new Float32Array(source);
  34198. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34199. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34200. }
  34201. }
  34202. return this._sourceNormals;
  34203. };
  34204. /**
  34205. * Updates the vertex buffer by applying transformation from the bones.
  34206. * Returns the Mesh.
  34207. *
  34208. * @param {skeleton} skeleton to apply
  34209. */
  34210. Mesh.prototype.applySkeleton = function (skeleton) {
  34211. if (!this.geometry) {
  34212. return this;
  34213. }
  34214. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34215. return this;
  34216. }
  34217. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34218. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34219. return this;
  34220. }
  34221. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34222. return this;
  34223. }
  34224. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34225. return this;
  34226. }
  34227. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34228. return this;
  34229. }
  34230. if (!this._sourcePositions) {
  34231. var submeshes = this.subMeshes.slice();
  34232. this.setPositionsForCPUSkinning();
  34233. this.subMeshes = submeshes;
  34234. }
  34235. if (!this._sourceNormals) {
  34236. this.setNormalsForCPUSkinning();
  34237. }
  34238. // positionsData checks for not being Float32Array will only pass at most once
  34239. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34240. if (!positionsData) {
  34241. return this;
  34242. }
  34243. if (!(positionsData instanceof Float32Array)) {
  34244. positionsData = new Float32Array(positionsData);
  34245. }
  34246. // normalsData checks for not being Float32Array will only pass at most once
  34247. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34248. if (!normalsData) {
  34249. return this;
  34250. }
  34251. if (!(normalsData instanceof Float32Array)) {
  34252. normalsData = new Float32Array(normalsData);
  34253. }
  34254. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34255. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34256. if (!matricesWeightsData || !matricesIndicesData) {
  34257. return this;
  34258. }
  34259. var needExtras = this.numBoneInfluencers > 4;
  34260. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34261. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34262. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34263. var tempVector3 = BABYLON.Vector3.Zero();
  34264. var finalMatrix = new BABYLON.Matrix();
  34265. var tempMatrix = new BABYLON.Matrix();
  34266. var matWeightIdx = 0;
  34267. var inf;
  34268. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34269. var weight;
  34270. for (inf = 0; inf < 4; inf++) {
  34271. weight = matricesWeightsData[matWeightIdx + inf];
  34272. if (weight > 0) {
  34273. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34274. finalMatrix.addToSelf(tempMatrix);
  34275. }
  34276. else
  34277. break;
  34278. }
  34279. if (needExtras) {
  34280. for (inf = 0; inf < 4; inf++) {
  34281. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34282. if (weight > 0) {
  34283. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34284. finalMatrix.addToSelf(tempMatrix);
  34285. }
  34286. else
  34287. break;
  34288. }
  34289. }
  34290. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34291. tempVector3.toArray(positionsData, index);
  34292. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34293. tempVector3.toArray(normalsData, index);
  34294. finalMatrix.reset();
  34295. }
  34296. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34297. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34298. return this;
  34299. };
  34300. // Tools
  34301. /**
  34302. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34303. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34304. */
  34305. Mesh.MinMax = function (meshes) {
  34306. var minVector = null;
  34307. var maxVector = null;
  34308. meshes.forEach(function (mesh, index, array) {
  34309. var boundingInfo = mesh.getBoundingInfo();
  34310. var boundingBox = boundingInfo.boundingBox;
  34311. if (!minVector || !maxVector) {
  34312. minVector = boundingBox.minimumWorld;
  34313. maxVector = boundingBox.maximumWorld;
  34314. }
  34315. else {
  34316. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34317. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34318. }
  34319. });
  34320. if (!minVector || !maxVector) {
  34321. return {
  34322. min: BABYLON.Vector3.Zero(),
  34323. max: BABYLON.Vector3.Zero()
  34324. };
  34325. }
  34326. return {
  34327. min: minVector,
  34328. max: maxVector
  34329. };
  34330. };
  34331. /**
  34332. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34333. */
  34334. Mesh.Center = function (meshesOrMinMaxVector) {
  34335. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34336. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34337. };
  34338. /**
  34339. * Merge the array of meshes into a single mesh for performance reasons.
  34340. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34341. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34342. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34343. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34344. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34345. */
  34346. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34347. if (disposeSource === void 0) { disposeSource = true; }
  34348. var index;
  34349. if (!allow32BitsIndices) {
  34350. var totalVertices = 0;
  34351. // Counting vertices
  34352. for (index = 0; index < meshes.length; index++) {
  34353. if (meshes[index]) {
  34354. totalVertices += meshes[index].getTotalVertices();
  34355. if (totalVertices > 65536) {
  34356. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34357. return null;
  34358. }
  34359. }
  34360. }
  34361. }
  34362. // Merge
  34363. var vertexData = null;
  34364. var otherVertexData;
  34365. var indiceArray = new Array();
  34366. var source = null;
  34367. for (index = 0; index < meshes.length; index++) {
  34368. if (meshes[index]) {
  34369. meshes[index].computeWorldMatrix(true);
  34370. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34371. otherVertexData.transform(meshes[index].getWorldMatrix());
  34372. if (vertexData) {
  34373. vertexData.merge(otherVertexData);
  34374. }
  34375. else {
  34376. vertexData = otherVertexData;
  34377. source = meshes[index];
  34378. }
  34379. if (subdivideWithSubMeshes) {
  34380. indiceArray.push(meshes[index].getTotalIndices());
  34381. }
  34382. }
  34383. }
  34384. source = source;
  34385. if (!meshSubclass) {
  34386. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34387. }
  34388. vertexData.applyToMesh(meshSubclass);
  34389. // Setting properties
  34390. meshSubclass.material = source.material;
  34391. meshSubclass.checkCollisions = source.checkCollisions;
  34392. // Cleaning
  34393. if (disposeSource) {
  34394. for (index = 0; index < meshes.length; index++) {
  34395. if (meshes[index]) {
  34396. meshes[index].dispose();
  34397. }
  34398. }
  34399. }
  34400. // Subdivide
  34401. if (subdivideWithSubMeshes) {
  34402. //-- removal of global submesh
  34403. meshSubclass.releaseSubMeshes();
  34404. index = 0;
  34405. var offset = 0;
  34406. //-- apply subdivision according to index table
  34407. while (index < indiceArray.length) {
  34408. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34409. offset += indiceArray[index];
  34410. index++;
  34411. }
  34412. }
  34413. return meshSubclass;
  34414. };
  34415. // Consts
  34416. Mesh._FRONTSIDE = 0;
  34417. Mesh._BACKSIDE = 1;
  34418. Mesh._DOUBLESIDE = 2;
  34419. Mesh._DEFAULTSIDE = 0;
  34420. Mesh._NO_CAP = 0;
  34421. Mesh._CAP_START = 1;
  34422. Mesh._CAP_END = 2;
  34423. Mesh._CAP_ALL = 3;
  34424. return Mesh;
  34425. }(BABYLON.AbstractMesh));
  34426. BABYLON.Mesh = Mesh;
  34427. })(BABYLON || (BABYLON = {}));
  34428. //# sourceMappingURL=babylon.mesh.js.map
  34429. var BABYLON;
  34430. (function (BABYLON) {
  34431. var BaseSubMesh = /** @class */ (function () {
  34432. function BaseSubMesh() {
  34433. }
  34434. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34435. get: function () {
  34436. return this._materialEffect;
  34437. },
  34438. enumerable: true,
  34439. configurable: true
  34440. });
  34441. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34442. if (defines === void 0) { defines = null; }
  34443. if (this._materialEffect === effect) {
  34444. if (!effect) {
  34445. this._materialDefines = null;
  34446. }
  34447. return;
  34448. }
  34449. this._materialDefines = defines;
  34450. this._materialEffect = effect;
  34451. };
  34452. return BaseSubMesh;
  34453. }());
  34454. BABYLON.BaseSubMesh = BaseSubMesh;
  34455. var SubMesh = /** @class */ (function (_super) {
  34456. __extends(SubMesh, _super);
  34457. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34458. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34459. var _this = _super.call(this) || this;
  34460. _this.materialIndex = materialIndex;
  34461. _this.verticesStart = verticesStart;
  34462. _this.verticesCount = verticesCount;
  34463. _this.indexStart = indexStart;
  34464. _this.indexCount = indexCount;
  34465. _this._renderId = 0;
  34466. _this._mesh = mesh;
  34467. _this._renderingMesh = renderingMesh || mesh;
  34468. mesh.subMeshes.push(_this);
  34469. _this._trianglePlanes = [];
  34470. _this._id = mesh.subMeshes.length - 1;
  34471. if (createBoundingBox) {
  34472. _this.refreshBoundingInfo();
  34473. mesh.computeWorldMatrix(true);
  34474. }
  34475. return _this;
  34476. }
  34477. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34478. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34479. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34480. };
  34481. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34482. get: function () {
  34483. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34484. },
  34485. enumerable: true,
  34486. configurable: true
  34487. });
  34488. /**
  34489. * Returns the submesh BoudingInfo object.
  34490. */
  34491. SubMesh.prototype.getBoundingInfo = function () {
  34492. if (this.IsGlobal) {
  34493. return this._mesh.getBoundingInfo();
  34494. }
  34495. return this._boundingInfo;
  34496. };
  34497. /**
  34498. * Sets the submesh BoundingInfo.
  34499. * Return the SubMesh.
  34500. */
  34501. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34502. this._boundingInfo = boundingInfo;
  34503. return this;
  34504. };
  34505. /**
  34506. * Returns the mesh of the current submesh.
  34507. */
  34508. SubMesh.prototype.getMesh = function () {
  34509. return this._mesh;
  34510. };
  34511. /**
  34512. * Returns the rendering mesh of the submesh.
  34513. */
  34514. SubMesh.prototype.getRenderingMesh = function () {
  34515. return this._renderingMesh;
  34516. };
  34517. /**
  34518. * Returns the submesh material.
  34519. */
  34520. SubMesh.prototype.getMaterial = function () {
  34521. var rootMaterial = this._renderingMesh.material;
  34522. if (rootMaterial === null || rootMaterial === undefined) {
  34523. return this._mesh.getScene().defaultMaterial;
  34524. }
  34525. else if (rootMaterial.getSubMaterial) {
  34526. var multiMaterial = rootMaterial;
  34527. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34528. if (this._currentMaterial !== effectiveMaterial) {
  34529. this._currentMaterial = effectiveMaterial;
  34530. this._materialDefines = null;
  34531. }
  34532. return effectiveMaterial;
  34533. }
  34534. return rootMaterial;
  34535. };
  34536. // Methods
  34537. /**
  34538. * Sets a new updated BoundingInfo object to the submesh.
  34539. * Returns the SubMesh.
  34540. */
  34541. SubMesh.prototype.refreshBoundingInfo = function () {
  34542. this._lastColliderWorldVertices = null;
  34543. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34544. return this;
  34545. }
  34546. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34547. if (!data) {
  34548. this._boundingInfo = this._mesh.getBoundingInfo();
  34549. return this;
  34550. }
  34551. var indices = this._renderingMesh.getIndices();
  34552. var extend;
  34553. //is this the only submesh?
  34554. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34555. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34556. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34557. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34558. }
  34559. else {
  34560. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34561. }
  34562. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34563. return this;
  34564. };
  34565. SubMesh.prototype._checkCollision = function (collider) {
  34566. var boundingInfo = this.getBoundingInfo();
  34567. return boundingInfo._checkCollision(collider);
  34568. };
  34569. /**
  34570. * Updates the submesh BoundingInfo.
  34571. * Returns the Submesh.
  34572. */
  34573. SubMesh.prototype.updateBoundingInfo = function (world) {
  34574. var boundingInfo = this.getBoundingInfo();
  34575. if (!boundingInfo) {
  34576. this.refreshBoundingInfo();
  34577. boundingInfo = this.getBoundingInfo();
  34578. }
  34579. boundingInfo.update(world);
  34580. return this;
  34581. };
  34582. /**
  34583. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34584. * Boolean returned.
  34585. */
  34586. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34587. var boundingInfo = this.getBoundingInfo();
  34588. if (!boundingInfo) {
  34589. return false;
  34590. }
  34591. return boundingInfo.isInFrustum(frustumPlanes);
  34592. };
  34593. /**
  34594. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34595. * Boolean returned.
  34596. */
  34597. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34598. var boundingInfo = this.getBoundingInfo();
  34599. if (!boundingInfo) {
  34600. return false;
  34601. }
  34602. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34603. };
  34604. /**
  34605. * Renders the submesh.
  34606. * Returns it.
  34607. */
  34608. SubMesh.prototype.render = function (enableAlphaMode) {
  34609. this._renderingMesh.render(this, enableAlphaMode);
  34610. return this;
  34611. };
  34612. /**
  34613. * Returns a new Index Buffer.
  34614. * Type returned : WebGLBuffer.
  34615. */
  34616. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34617. if (!this._linesIndexBuffer) {
  34618. var linesIndices = [];
  34619. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34620. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34621. }
  34622. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34623. this.linesIndexCount = linesIndices.length;
  34624. }
  34625. return this._linesIndexBuffer;
  34626. };
  34627. /**
  34628. * True is the passed Ray intersects the submesh bounding box.
  34629. * Boolean returned.
  34630. */
  34631. SubMesh.prototype.canIntersects = function (ray) {
  34632. var boundingInfo = this.getBoundingInfo();
  34633. if (!boundingInfo) {
  34634. return false;
  34635. }
  34636. return ray.intersectsBox(boundingInfo.boundingBox);
  34637. };
  34638. /**
  34639. * Returns an object IntersectionInfo.
  34640. */
  34641. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34642. var intersectInfo = null;
  34643. var material = this.getMaterial();
  34644. if (!material) {
  34645. return null;
  34646. }
  34647. switch (material.fillMode) {
  34648. case BABYLON.Material.PointListDrawMode:
  34649. case BABYLON.Material.LineListDrawMode:
  34650. case BABYLON.Material.LineLoopDrawMode:
  34651. case BABYLON.Material.LineStripDrawMode:
  34652. case BABYLON.Material.TriangleFanDrawMode:
  34653. case BABYLON.Material.TriangleStripDrawMode:
  34654. return null;
  34655. }
  34656. // LineMesh first as it's also a Mesh...
  34657. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34658. var lineMesh = this._mesh;
  34659. // Line test
  34660. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34661. var p0 = positions[indices[index]];
  34662. var p1 = positions[indices[index + 1]];
  34663. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34664. if (length < 0) {
  34665. continue;
  34666. }
  34667. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34668. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34669. if (fastCheck) {
  34670. break;
  34671. }
  34672. }
  34673. }
  34674. }
  34675. else {
  34676. // Triangles test
  34677. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34678. var p0 = positions[indices[index]];
  34679. var p1 = positions[indices[index + 1]];
  34680. var p2 = positions[indices[index + 2]];
  34681. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34682. if (currentIntersectInfo) {
  34683. if (currentIntersectInfo.distance < 0) {
  34684. continue;
  34685. }
  34686. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34687. intersectInfo = currentIntersectInfo;
  34688. intersectInfo.faceId = index / 3;
  34689. if (fastCheck) {
  34690. break;
  34691. }
  34692. }
  34693. }
  34694. }
  34695. }
  34696. return intersectInfo;
  34697. };
  34698. SubMesh.prototype._rebuild = function () {
  34699. if (this._linesIndexBuffer) {
  34700. this._linesIndexBuffer = null;
  34701. }
  34702. };
  34703. // Clone
  34704. /**
  34705. * Creates a new Submesh from the passed Mesh.
  34706. */
  34707. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34708. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34709. if (!this.IsGlobal) {
  34710. var boundingInfo = this.getBoundingInfo();
  34711. if (!boundingInfo) {
  34712. return result;
  34713. }
  34714. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34715. }
  34716. return result;
  34717. };
  34718. // Dispose
  34719. /**
  34720. * Disposes the Submesh.
  34721. * Returns nothing.
  34722. */
  34723. SubMesh.prototype.dispose = function () {
  34724. if (this._linesIndexBuffer) {
  34725. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34726. this._linesIndexBuffer = null;
  34727. }
  34728. // Remove from mesh
  34729. var index = this._mesh.subMeshes.indexOf(this);
  34730. this._mesh.subMeshes.splice(index, 1);
  34731. };
  34732. // Statics
  34733. /**
  34734. * Creates a new Submesh from the passed parameters :
  34735. * - materialIndex (integer) : the index of the main mesh material.
  34736. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34737. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34738. * - mesh (Mesh) : the main mesh to create the submesh from.
  34739. * - renderingMesh (optional Mesh) : rendering mesh.
  34740. */
  34741. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34742. var minVertexIndex = Number.MAX_VALUE;
  34743. var maxVertexIndex = -Number.MAX_VALUE;
  34744. renderingMesh = (renderingMesh || mesh);
  34745. var indices = renderingMesh.getIndices();
  34746. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34747. var vertexIndex = indices[index];
  34748. if (vertexIndex < minVertexIndex)
  34749. minVertexIndex = vertexIndex;
  34750. if (vertexIndex > maxVertexIndex)
  34751. maxVertexIndex = vertexIndex;
  34752. }
  34753. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34754. };
  34755. return SubMesh;
  34756. }(BaseSubMesh));
  34757. BABYLON.SubMesh = SubMesh;
  34758. })(BABYLON || (BABYLON = {}));
  34759. //# sourceMappingURL=babylon.subMesh.js.map
  34760. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34761. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34762. s = arguments[i];
  34763. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34764. t[p] = s[p];
  34765. }
  34766. return t;
  34767. };
  34768. var BABYLON;
  34769. (function (BABYLON) {
  34770. /**
  34771. * Manages the defines for the Material
  34772. */
  34773. var MaterialDefines = /** @class */ (function () {
  34774. function MaterialDefines() {
  34775. this._isDirty = true;
  34776. /** @hidden */
  34777. this._areLightsDirty = true;
  34778. /** @hidden */
  34779. this._areAttributesDirty = true;
  34780. /** @hidden */
  34781. this._areTexturesDirty = true;
  34782. /** @hidden */
  34783. this._areFresnelDirty = true;
  34784. /** @hidden */
  34785. this._areMiscDirty = true;
  34786. /** @hidden */
  34787. this._areImageProcessingDirty = true;
  34788. /** @hidden */
  34789. this._normals = false;
  34790. /** @hidden */
  34791. this._uvs = false;
  34792. /** @hidden */
  34793. this._needNormals = false;
  34794. /** @hidden */
  34795. this._needUVs = false;
  34796. }
  34797. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34798. /**
  34799. * Specifies if the material needs to be re-calculated
  34800. */
  34801. get: function () {
  34802. return this._isDirty;
  34803. },
  34804. enumerable: true,
  34805. configurable: true
  34806. });
  34807. /**
  34808. * Marks the material to indicate that it has been re-calculated
  34809. */
  34810. MaterialDefines.prototype.markAsProcessed = function () {
  34811. this._isDirty = false;
  34812. this._areAttributesDirty = false;
  34813. this._areTexturesDirty = false;
  34814. this._areFresnelDirty = false;
  34815. this._areLightsDirty = false;
  34816. this._areMiscDirty = false;
  34817. this._areImageProcessingDirty = false;
  34818. };
  34819. /**
  34820. * Marks the material to indicate that it needs to be re-calculated
  34821. */
  34822. MaterialDefines.prototype.markAsUnprocessed = function () {
  34823. this._isDirty = true;
  34824. };
  34825. /**
  34826. * Marks the material to indicate all of its defines need to be re-calculated
  34827. */
  34828. MaterialDefines.prototype.markAllAsDirty = function () {
  34829. this._areTexturesDirty = true;
  34830. this._areAttributesDirty = true;
  34831. this._areLightsDirty = true;
  34832. this._areFresnelDirty = true;
  34833. this._areMiscDirty = true;
  34834. this._areImageProcessingDirty = true;
  34835. this._isDirty = true;
  34836. };
  34837. /**
  34838. * Marks the material to indicate that image processing needs to be re-calculated
  34839. */
  34840. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34841. this._areImageProcessingDirty = true;
  34842. this._isDirty = true;
  34843. };
  34844. /**
  34845. * Marks the material to indicate the lights need to be re-calculated
  34846. */
  34847. MaterialDefines.prototype.markAsLightDirty = function () {
  34848. this._areLightsDirty = true;
  34849. this._isDirty = true;
  34850. };
  34851. /**
  34852. * Marks the attribute state as changed
  34853. */
  34854. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34855. this._areAttributesDirty = true;
  34856. this._isDirty = true;
  34857. };
  34858. /**
  34859. * Marks the texture state as changed
  34860. */
  34861. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34862. this._areTexturesDirty = true;
  34863. this._isDirty = true;
  34864. };
  34865. /**
  34866. * Marks the fresnel state as changed
  34867. */
  34868. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34869. this._areFresnelDirty = true;
  34870. this._isDirty = true;
  34871. };
  34872. /**
  34873. * Marks the misc state as changed
  34874. */
  34875. MaterialDefines.prototype.markAsMiscDirty = function () {
  34876. this._areMiscDirty = true;
  34877. this._isDirty = true;
  34878. };
  34879. /**
  34880. * Rebuilds the material defines
  34881. */
  34882. MaterialDefines.prototype.rebuild = function () {
  34883. if (this._keys) {
  34884. delete this._keys;
  34885. }
  34886. this._keys = [];
  34887. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34888. var key = _a[_i];
  34889. if (key[0] === "_") {
  34890. continue;
  34891. }
  34892. this._keys.push(key);
  34893. }
  34894. };
  34895. /**
  34896. * Specifies if two material defines are equal
  34897. * @param other - A material define instance to compare to
  34898. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34899. */
  34900. MaterialDefines.prototype.isEqual = function (other) {
  34901. if (this._keys.length !== other._keys.length) {
  34902. return false;
  34903. }
  34904. for (var index = 0; index < this._keys.length; index++) {
  34905. var prop = this._keys[index];
  34906. if (this[prop] !== other[prop]) {
  34907. return false;
  34908. }
  34909. }
  34910. return true;
  34911. };
  34912. /**
  34913. * Clones this instance's defines to another instance
  34914. * @param other - material defines to clone values to
  34915. */
  34916. MaterialDefines.prototype.cloneTo = function (other) {
  34917. if (this._keys.length !== other._keys.length) {
  34918. other._keys = this._keys.slice(0);
  34919. }
  34920. for (var index = 0; index < this._keys.length; index++) {
  34921. var prop = this._keys[index];
  34922. other[prop] = this[prop];
  34923. }
  34924. };
  34925. /**
  34926. * Resets the material define values
  34927. */
  34928. MaterialDefines.prototype.reset = function () {
  34929. for (var index = 0; index < this._keys.length; index++) {
  34930. var prop = this._keys[index];
  34931. var type = typeof this[prop];
  34932. switch (type) {
  34933. case "number":
  34934. this[prop] = 0;
  34935. break;
  34936. case "string":
  34937. this[prop] = "";
  34938. break;
  34939. default:
  34940. this[prop] = false;
  34941. break;
  34942. }
  34943. }
  34944. };
  34945. /**
  34946. * Converts the material define values to a string
  34947. * @returns - String of material define information
  34948. */
  34949. MaterialDefines.prototype.toString = function () {
  34950. var result = "";
  34951. for (var index = 0; index < this._keys.length; index++) {
  34952. var prop = this._keys[index];
  34953. var value = this[prop];
  34954. var type = typeof value;
  34955. switch (type) {
  34956. case "number":
  34957. case "string":
  34958. result += "#define " + prop + " " + value + "\n";
  34959. break;
  34960. default:
  34961. if (value) {
  34962. result += "#define " + prop + "\n";
  34963. }
  34964. break;
  34965. }
  34966. }
  34967. return result;
  34968. };
  34969. return MaterialDefines;
  34970. }());
  34971. BABYLON.MaterialDefines = MaterialDefines;
  34972. /**
  34973. * Base class for the main features of a material in Babylon.js
  34974. */
  34975. var Material = /** @class */ (function () {
  34976. /**
  34977. * Creates a material instance
  34978. * @param name defines the name of the material
  34979. * @param scene defines the scene to reference
  34980. * @param doNotAdd specifies if the material should be added to the scene
  34981. */
  34982. function Material(name, scene, doNotAdd) {
  34983. /**
  34984. * Specifies if the ready state should be checked on each call
  34985. */
  34986. this.checkReadyOnEveryCall = false;
  34987. /**
  34988. * Specifies if the ready state should be checked once
  34989. */
  34990. this.checkReadyOnlyOnce = false;
  34991. /**
  34992. * The state of the material
  34993. */
  34994. this.state = "";
  34995. /**
  34996. * The alpha value of the material
  34997. */
  34998. this._alpha = 1.0;
  34999. /**
  35000. * Specifies if back face culling is enabled
  35001. */
  35002. this._backFaceCulling = true;
  35003. /**
  35004. * Specifies if the material should be serialized
  35005. */
  35006. this.doNotSerialize = false;
  35007. /**
  35008. * Specifies if the effect should be stored on sub meshes
  35009. */
  35010. this.storeEffectOnSubMeshes = false;
  35011. /**
  35012. * An event triggered when the material is disposed
  35013. */
  35014. this.onDisposeObservable = new BABYLON.Observable();
  35015. /**
  35016. * An event triggered when the material is bound
  35017. */
  35018. this.onBindObservable = new BABYLON.Observable();
  35019. /**
  35020. * An event triggered when the material is unbound
  35021. */
  35022. this.onUnBindObservable = new BABYLON.Observable();
  35023. /**
  35024. * Stores the value of the alpha mode
  35025. */
  35026. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  35027. /**
  35028. * Stores the state of the need depth pre-pass value
  35029. */
  35030. this._needDepthPrePass = false;
  35031. /**
  35032. * Specifies if depth writing should be disabled
  35033. */
  35034. this.disableDepthWrite = false;
  35035. /**
  35036. * Specifies if depth writing should be forced
  35037. */
  35038. this.forceDepthWrite = false;
  35039. /**
  35040. * Specifies if there should be a separate pass for culling
  35041. */
  35042. this.separateCullingPass = false;
  35043. /**
  35044. * Stores the state specifing if fog should be enabled
  35045. */
  35046. this._fogEnabled = true;
  35047. /**
  35048. * Stores the size of points
  35049. */
  35050. this.pointSize = 1.0;
  35051. /**
  35052. * Stores the z offset value
  35053. */
  35054. this.zOffset = 0;
  35055. /**
  35056. * Specifies if the material was previously ready
  35057. */
  35058. this._wasPreviouslyReady = false;
  35059. /**
  35060. * Stores the fill mode state
  35061. */
  35062. this._fillMode = Material.TriangleFillMode;
  35063. this.name = name;
  35064. this.id = name || BABYLON.Tools.RandomId();
  35065. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35066. this.uniqueId = this._scene.getUniqueId();
  35067. if (this._scene.useRightHandedSystem) {
  35068. this.sideOrientation = Material.ClockWiseSideOrientation;
  35069. }
  35070. else {
  35071. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  35072. }
  35073. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  35074. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  35075. if (!doNotAdd) {
  35076. this._scene.materials.push(this);
  35077. }
  35078. }
  35079. Object.defineProperty(Material, "TriangleFillMode", {
  35080. /**
  35081. * Returns the triangle fill mode
  35082. */
  35083. get: function () {
  35084. return Material._TriangleFillMode;
  35085. },
  35086. enumerable: true,
  35087. configurable: true
  35088. });
  35089. Object.defineProperty(Material, "WireFrameFillMode", {
  35090. /**
  35091. * Returns the wireframe mode
  35092. */
  35093. get: function () {
  35094. return Material._WireFrameFillMode;
  35095. },
  35096. enumerable: true,
  35097. configurable: true
  35098. });
  35099. Object.defineProperty(Material, "PointFillMode", {
  35100. /**
  35101. * Returns the point fill mode
  35102. */
  35103. get: function () {
  35104. return Material._PointFillMode;
  35105. },
  35106. enumerable: true,
  35107. configurable: true
  35108. });
  35109. Object.defineProperty(Material, "PointListDrawMode", {
  35110. /**
  35111. * Returns the point list draw mode
  35112. */
  35113. get: function () {
  35114. return Material._PointListDrawMode;
  35115. },
  35116. enumerable: true,
  35117. configurable: true
  35118. });
  35119. Object.defineProperty(Material, "LineListDrawMode", {
  35120. /**
  35121. * Returns the line list draw mode
  35122. */
  35123. get: function () {
  35124. return Material._LineListDrawMode;
  35125. },
  35126. enumerable: true,
  35127. configurable: true
  35128. });
  35129. Object.defineProperty(Material, "LineLoopDrawMode", {
  35130. /**
  35131. * Returns the line loop draw mode
  35132. */
  35133. get: function () {
  35134. return Material._LineLoopDrawMode;
  35135. },
  35136. enumerable: true,
  35137. configurable: true
  35138. });
  35139. Object.defineProperty(Material, "LineStripDrawMode", {
  35140. /**
  35141. * Returns the line strip draw mode
  35142. */
  35143. get: function () {
  35144. return Material._LineStripDrawMode;
  35145. },
  35146. enumerable: true,
  35147. configurable: true
  35148. });
  35149. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35150. /**
  35151. * Returns the triangle strip draw mode
  35152. */
  35153. get: function () {
  35154. return Material._TriangleStripDrawMode;
  35155. },
  35156. enumerable: true,
  35157. configurable: true
  35158. });
  35159. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35160. /**
  35161. * Returns the triangle fan draw mode
  35162. */
  35163. get: function () {
  35164. return Material._TriangleFanDrawMode;
  35165. },
  35166. enumerable: true,
  35167. configurable: true
  35168. });
  35169. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35170. /**
  35171. * Returns the clock-wise side orientation
  35172. */
  35173. get: function () {
  35174. return Material._ClockWiseSideOrientation;
  35175. },
  35176. enumerable: true,
  35177. configurable: true
  35178. });
  35179. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35180. /**
  35181. * Returns the counter clock-wise side orientation
  35182. */
  35183. get: function () {
  35184. return Material._CounterClockWiseSideOrientation;
  35185. },
  35186. enumerable: true,
  35187. configurable: true
  35188. });
  35189. Object.defineProperty(Material, "TextureDirtyFlag", {
  35190. /**
  35191. * Returns the dirty texture flag value
  35192. */
  35193. get: function () {
  35194. return Material._TextureDirtyFlag;
  35195. },
  35196. enumerable: true,
  35197. configurable: true
  35198. });
  35199. Object.defineProperty(Material, "LightDirtyFlag", {
  35200. /**
  35201. * Returns the dirty light flag value
  35202. */
  35203. get: function () {
  35204. return Material._LightDirtyFlag;
  35205. },
  35206. enumerable: true,
  35207. configurable: true
  35208. });
  35209. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35210. /**
  35211. * Returns the dirty fresnel flag value
  35212. */
  35213. get: function () {
  35214. return Material._FresnelDirtyFlag;
  35215. },
  35216. enumerable: true,
  35217. configurable: true
  35218. });
  35219. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35220. /**
  35221. * Returns the dirty attributes flag value
  35222. */
  35223. get: function () {
  35224. return Material._AttributesDirtyFlag;
  35225. },
  35226. enumerable: true,
  35227. configurable: true
  35228. });
  35229. Object.defineProperty(Material, "MiscDirtyFlag", {
  35230. /**
  35231. * Returns the dirty misc flag value
  35232. */
  35233. get: function () {
  35234. return Material._MiscDirtyFlag;
  35235. },
  35236. enumerable: true,
  35237. configurable: true
  35238. });
  35239. Object.defineProperty(Material.prototype, "alpha", {
  35240. /**
  35241. * Gets the alpha value of the material
  35242. */
  35243. get: function () {
  35244. return this._alpha;
  35245. },
  35246. /**
  35247. * Sets the alpha value of the material
  35248. */
  35249. set: function (value) {
  35250. if (this._alpha === value) {
  35251. return;
  35252. }
  35253. this._alpha = value;
  35254. this.markAsDirty(Material.MiscDirtyFlag);
  35255. },
  35256. enumerable: true,
  35257. configurable: true
  35258. });
  35259. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35260. /**
  35261. * Gets the back-face culling state
  35262. */
  35263. get: function () {
  35264. return this._backFaceCulling;
  35265. },
  35266. /**
  35267. * Sets the back-face culling state
  35268. */
  35269. set: function (value) {
  35270. if (this._backFaceCulling === value) {
  35271. return;
  35272. }
  35273. this._backFaceCulling = value;
  35274. this.markAsDirty(Material.TextureDirtyFlag);
  35275. },
  35276. enumerable: true,
  35277. configurable: true
  35278. });
  35279. Object.defineProperty(Material.prototype, "onDispose", {
  35280. /**
  35281. * Called during a dispose event
  35282. */
  35283. set: function (callback) {
  35284. if (this._onDisposeObserver) {
  35285. this.onDisposeObservable.remove(this._onDisposeObserver);
  35286. }
  35287. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35288. },
  35289. enumerable: true,
  35290. configurable: true
  35291. });
  35292. Object.defineProperty(Material.prototype, "onBind", {
  35293. /**
  35294. * Called during a bind event
  35295. */
  35296. set: function (callback) {
  35297. if (this._onBindObserver) {
  35298. this.onBindObservable.remove(this._onBindObserver);
  35299. }
  35300. this._onBindObserver = this.onBindObservable.add(callback);
  35301. },
  35302. enumerable: true,
  35303. configurable: true
  35304. });
  35305. Object.defineProperty(Material.prototype, "alphaMode", {
  35306. /**
  35307. * Gets the value of the alpha mode
  35308. */
  35309. get: function () {
  35310. return this._alphaMode;
  35311. },
  35312. /**
  35313. * Sets the value of the alpha mode.
  35314. *
  35315. * | Value | Type | Description |
  35316. * | --- | --- | --- |
  35317. * | 0 | ALPHA_DISABLE | |
  35318. * | 1 | ALPHA_ADD | |
  35319. * | 2 | ALPHA_COMBINE | |
  35320. * | 3 | ALPHA_SUBTRACT | |
  35321. * | 4 | ALPHA_MULTIPLY | |
  35322. * | 5 | ALPHA_MAXIMIZED | |
  35323. * | 6 | ALPHA_ONEONE | |
  35324. * | 7 | ALPHA_PREMULTIPLIED | |
  35325. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35326. * | 9 | ALPHA_INTERPOLATE | |
  35327. * | 10 | ALPHA_SCREENMODE | |
  35328. *
  35329. */
  35330. set: function (value) {
  35331. if (this._alphaMode === value) {
  35332. return;
  35333. }
  35334. this._alphaMode = value;
  35335. this.markAsDirty(Material.TextureDirtyFlag);
  35336. },
  35337. enumerable: true,
  35338. configurable: true
  35339. });
  35340. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35341. /**
  35342. * Gets the depth pre-pass value
  35343. */
  35344. get: function () {
  35345. return this._needDepthPrePass;
  35346. },
  35347. /**
  35348. * Sets the need depth pre-pass value
  35349. */
  35350. set: function (value) {
  35351. if (this._needDepthPrePass === value) {
  35352. return;
  35353. }
  35354. this._needDepthPrePass = value;
  35355. if (this._needDepthPrePass) {
  35356. this.checkReadyOnEveryCall = true;
  35357. }
  35358. },
  35359. enumerable: true,
  35360. configurable: true
  35361. });
  35362. Object.defineProperty(Material.prototype, "fogEnabled", {
  35363. /**
  35364. * Gets the value of the fog enabled state
  35365. */
  35366. get: function () {
  35367. return this._fogEnabled;
  35368. },
  35369. /**
  35370. * Sets the state for enabling fog
  35371. */
  35372. set: function (value) {
  35373. if (this._fogEnabled === value) {
  35374. return;
  35375. }
  35376. this._fogEnabled = value;
  35377. this.markAsDirty(Material.MiscDirtyFlag);
  35378. },
  35379. enumerable: true,
  35380. configurable: true
  35381. });
  35382. Object.defineProperty(Material.prototype, "wireframe", {
  35383. /**
  35384. * Gets a value specifying if wireframe mode is enabled
  35385. */
  35386. get: function () {
  35387. switch (this._fillMode) {
  35388. case Material.WireFrameFillMode:
  35389. case Material.LineListDrawMode:
  35390. case Material.LineLoopDrawMode:
  35391. case Material.LineStripDrawMode:
  35392. return true;
  35393. }
  35394. return this._scene.forceWireframe;
  35395. },
  35396. /**
  35397. * Sets the state of wireframe mode
  35398. */
  35399. set: function (value) {
  35400. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35401. },
  35402. enumerable: true,
  35403. configurable: true
  35404. });
  35405. Object.defineProperty(Material.prototype, "pointsCloud", {
  35406. /**
  35407. * Gets the value specifying if point clouds are enabled
  35408. */
  35409. get: function () {
  35410. switch (this._fillMode) {
  35411. case Material.PointFillMode:
  35412. case Material.PointListDrawMode:
  35413. return true;
  35414. }
  35415. return this._scene.forcePointsCloud;
  35416. },
  35417. /**
  35418. * Sets the state of point cloud mode
  35419. */
  35420. set: function (value) {
  35421. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35422. },
  35423. enumerable: true,
  35424. configurable: true
  35425. });
  35426. Object.defineProperty(Material.prototype, "fillMode", {
  35427. /**
  35428. * Gets the material fill mode
  35429. */
  35430. get: function () {
  35431. return this._fillMode;
  35432. },
  35433. /**
  35434. * Sets the material fill mode
  35435. */
  35436. set: function (value) {
  35437. if (this._fillMode === value) {
  35438. return;
  35439. }
  35440. this._fillMode = value;
  35441. this.markAsDirty(Material.MiscDirtyFlag);
  35442. },
  35443. enumerable: true,
  35444. configurable: true
  35445. });
  35446. /**
  35447. * Returns a string representation of the current material
  35448. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35449. * @returns a string with material information
  35450. */
  35451. Material.prototype.toString = function (fullDetails) {
  35452. var ret = "Name: " + this.name;
  35453. if (fullDetails) {
  35454. }
  35455. return ret;
  35456. };
  35457. /**
  35458. * Gets the class name of the material
  35459. * @returns a string with the class name of the material
  35460. */
  35461. Material.prototype.getClassName = function () {
  35462. return "Material";
  35463. };
  35464. Object.defineProperty(Material.prototype, "isFrozen", {
  35465. /**
  35466. * Specifies if updates for the material been locked
  35467. */
  35468. get: function () {
  35469. return this.checkReadyOnlyOnce;
  35470. },
  35471. enumerable: true,
  35472. configurable: true
  35473. });
  35474. /**
  35475. * Locks updates for the material
  35476. */
  35477. Material.prototype.freeze = function () {
  35478. this.checkReadyOnlyOnce = true;
  35479. };
  35480. /**
  35481. * Unlocks updates for the material
  35482. */
  35483. Material.prototype.unfreeze = function () {
  35484. this.checkReadyOnlyOnce = false;
  35485. };
  35486. /**
  35487. * Specifies if the material is ready to be used
  35488. * @param mesh defines the mesh to check
  35489. * @param useInstances specifies if instances should be used
  35490. * @returns a boolean indicating if the material is ready to be used
  35491. */
  35492. Material.prototype.isReady = function (mesh, useInstances) {
  35493. return true;
  35494. };
  35495. /**
  35496. * Specifies that the submesh is ready to be used
  35497. * @param mesh defines the mesh to check
  35498. * @param subMesh defines which submesh to check
  35499. * @param useInstances specifies that instances should be used
  35500. * @returns a boolean indicating that the submesh is ready or not
  35501. */
  35502. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35503. return false;
  35504. };
  35505. /**
  35506. * Returns the material effect
  35507. * @returns the effect associated with the material
  35508. */
  35509. Material.prototype.getEffect = function () {
  35510. return this._effect;
  35511. };
  35512. /**
  35513. * Returns the current scene
  35514. * @returns a Scene
  35515. */
  35516. Material.prototype.getScene = function () {
  35517. return this._scene;
  35518. };
  35519. /**
  35520. * Specifies if the material will require alpha blending
  35521. * @returns a boolean specifying if alpha blending is needed
  35522. */
  35523. Material.prototype.needAlphaBlending = function () {
  35524. return (this.alpha < 1.0);
  35525. };
  35526. /**
  35527. * Specifies if the mesh will require alpha blending
  35528. * @param mesh defines the mesh to check
  35529. * @returns a boolean specifying if alpha blending is needed for the mesh
  35530. */
  35531. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35532. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35533. };
  35534. /**
  35535. * Specifies if this material should be rendered in alpha test mode
  35536. * @returns a boolean specifying if an alpha test is needed.
  35537. */
  35538. Material.prototype.needAlphaTesting = function () {
  35539. return false;
  35540. };
  35541. /**
  35542. * Gets the texture used for the alpha test
  35543. * @returns the texture to use for alpha testing
  35544. */
  35545. Material.prototype.getAlphaTestTexture = function () {
  35546. return null;
  35547. };
  35548. /**
  35549. * Marks the material to indicate that it needs to be re-calculated
  35550. */
  35551. Material.prototype.markDirty = function () {
  35552. this._wasPreviouslyReady = false;
  35553. };
  35554. /** @hidden */
  35555. Material.prototype._preBind = function (effect, overrideOrientation) {
  35556. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35557. var engine = this._scene.getEngine();
  35558. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35559. var reverse = orientation === Material.ClockWiseSideOrientation;
  35560. engine.enableEffect(effect ? effect : this._effect);
  35561. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35562. return reverse;
  35563. };
  35564. /**
  35565. * Binds the material to the mesh
  35566. * @param world defines the world transformation matrix
  35567. * @param mesh defines the mesh to bind the material to
  35568. */
  35569. Material.prototype.bind = function (world, mesh) {
  35570. };
  35571. /**
  35572. * Binds the submesh to the material
  35573. * @param world defines the world transformation matrix
  35574. * @param mesh defines the mesh containing the submesh
  35575. * @param subMesh defines the submesh to bind the material to
  35576. */
  35577. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35578. };
  35579. /**
  35580. * Binds the world matrix to the material
  35581. * @param world defines the world transformation matrix
  35582. */
  35583. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35584. };
  35585. /**
  35586. * Binds the scene's uniform buffer to the effect.
  35587. * @param effect defines the effect to bind to the scene uniform buffer
  35588. * @param sceneUbo defines the uniform buffer storing scene data
  35589. */
  35590. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35591. sceneUbo.bindToEffect(effect, "Scene");
  35592. };
  35593. /**
  35594. * Binds the view matrix to the effect
  35595. * @param effect defines the effect to bind the view matrix to
  35596. */
  35597. Material.prototype.bindView = function (effect) {
  35598. if (!this._useUBO) {
  35599. effect.setMatrix("view", this.getScene().getViewMatrix());
  35600. }
  35601. else {
  35602. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35603. }
  35604. };
  35605. /**
  35606. * Binds the view projection matrix to the effect
  35607. * @param effect defines the effect to bind the view projection matrix to
  35608. */
  35609. Material.prototype.bindViewProjection = function (effect) {
  35610. if (!this._useUBO) {
  35611. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35612. }
  35613. else {
  35614. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35615. }
  35616. };
  35617. /**
  35618. * Specifies if material alpha testing should be turned on for the mesh
  35619. * @param mesh defines the mesh to check
  35620. */
  35621. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35622. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35623. };
  35624. /**
  35625. * Processes to execute after binding the material to a mesh
  35626. * @param mesh defines the rendered mesh
  35627. */
  35628. Material.prototype._afterBind = function (mesh) {
  35629. this._scene._cachedMaterial = this;
  35630. if (mesh) {
  35631. this._scene._cachedVisibility = mesh.visibility;
  35632. }
  35633. else {
  35634. this._scene._cachedVisibility = 1;
  35635. }
  35636. if (mesh) {
  35637. this.onBindObservable.notifyObservers(mesh);
  35638. }
  35639. if (this.disableDepthWrite) {
  35640. var engine = this._scene.getEngine();
  35641. this._cachedDepthWriteState = engine.getDepthWrite();
  35642. engine.setDepthWrite(false);
  35643. }
  35644. };
  35645. /**
  35646. * Unbinds the material from the mesh
  35647. */
  35648. Material.prototype.unbind = function () {
  35649. this.onUnBindObservable.notifyObservers(this);
  35650. if (this.disableDepthWrite) {
  35651. var engine = this._scene.getEngine();
  35652. engine.setDepthWrite(this._cachedDepthWriteState);
  35653. }
  35654. };
  35655. /**
  35656. * Gets the active textures from the material
  35657. * @returns an array of textures
  35658. */
  35659. Material.prototype.getActiveTextures = function () {
  35660. return [];
  35661. };
  35662. /**
  35663. * Specifies if the material uses a texture
  35664. * @param texture defines the texture to check against the material
  35665. * @returns a boolean specifying if the material uses the texture
  35666. */
  35667. Material.prototype.hasTexture = function (texture) {
  35668. return false;
  35669. };
  35670. /**
  35671. * Makes a duplicate of the material, and gives it a new name
  35672. * @param name defines the new name for the duplicated material
  35673. * @returns the cloned material
  35674. */
  35675. Material.prototype.clone = function (name) {
  35676. return null;
  35677. };
  35678. /**
  35679. * Gets the meshes bound to the material
  35680. * @returns an array of meshes bound to the material
  35681. */
  35682. Material.prototype.getBindedMeshes = function () {
  35683. var result = new Array();
  35684. for (var index = 0; index < this._scene.meshes.length; index++) {
  35685. var mesh = this._scene.meshes[index];
  35686. if (mesh.material === this) {
  35687. result.push(mesh);
  35688. }
  35689. }
  35690. return result;
  35691. };
  35692. /**
  35693. * Force shader compilation
  35694. * @param mesh defines the mesh associated with this material
  35695. * @param onCompiled defines a function to execute once the material is compiled
  35696. * @param options defines the options to configure the compilation
  35697. */
  35698. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35699. var _this = this;
  35700. var localOptions = __assign({ clipPlane: false }, options);
  35701. var subMesh = new BABYLON.BaseSubMesh();
  35702. var scene = this.getScene();
  35703. var checkReady = function () {
  35704. if (!_this._scene || !_this._scene.getEngine()) {
  35705. return;
  35706. }
  35707. if (subMesh._materialDefines) {
  35708. subMesh._materialDefines._renderId = -1;
  35709. }
  35710. var clipPlaneState = scene.clipPlane;
  35711. if (localOptions.clipPlane) {
  35712. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35713. }
  35714. if (_this.storeEffectOnSubMeshes) {
  35715. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35716. if (onCompiled) {
  35717. onCompiled(_this);
  35718. }
  35719. }
  35720. else {
  35721. setTimeout(checkReady, 16);
  35722. }
  35723. }
  35724. else {
  35725. if (_this.isReady(mesh)) {
  35726. if (onCompiled) {
  35727. onCompiled(_this);
  35728. }
  35729. }
  35730. else {
  35731. setTimeout(checkReady, 16);
  35732. }
  35733. }
  35734. if (localOptions.clipPlane) {
  35735. scene.clipPlane = clipPlaneState;
  35736. }
  35737. };
  35738. checkReady();
  35739. };
  35740. /**
  35741. * Force shader compilation
  35742. * @param mesh defines the mesh that will use this material
  35743. * @param options defines additional options for compiling the shaders
  35744. * @returns a promise that resolves when the compilation completes
  35745. */
  35746. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35747. var _this = this;
  35748. return new Promise(function (resolve) {
  35749. _this.forceCompilation(mesh, function () {
  35750. resolve();
  35751. }, options);
  35752. });
  35753. };
  35754. /**
  35755. * Marks a define in the material to indicate that it needs to be re-computed
  35756. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35757. */
  35758. Material.prototype.markAsDirty = function (flag) {
  35759. if (flag & Material.TextureDirtyFlag) {
  35760. this._markAllSubMeshesAsTexturesDirty();
  35761. }
  35762. if (flag & Material.LightDirtyFlag) {
  35763. this._markAllSubMeshesAsLightsDirty();
  35764. }
  35765. if (flag & Material.FresnelDirtyFlag) {
  35766. this._markAllSubMeshesAsFresnelDirty();
  35767. }
  35768. if (flag & Material.AttributesDirtyFlag) {
  35769. this._markAllSubMeshesAsAttributesDirty();
  35770. }
  35771. if (flag & Material.MiscDirtyFlag) {
  35772. this._markAllSubMeshesAsMiscDirty();
  35773. }
  35774. this.getScene().resetCachedMaterial();
  35775. };
  35776. /**
  35777. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35778. * @param func defines a function which checks material defines against the submeshes
  35779. */
  35780. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35781. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35782. var mesh = _a[_i];
  35783. if (!mesh.subMeshes) {
  35784. continue;
  35785. }
  35786. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35787. var subMesh = _c[_b];
  35788. if (subMesh.getMaterial() !== this) {
  35789. continue;
  35790. }
  35791. if (!subMesh._materialDefines) {
  35792. continue;
  35793. }
  35794. func(subMesh._materialDefines);
  35795. }
  35796. }
  35797. };
  35798. /**
  35799. * Indicates that image processing needs to be re-calculated for all submeshes
  35800. */
  35801. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35802. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35803. };
  35804. /**
  35805. * Indicates that textures need to be re-calculated for all submeshes
  35806. */
  35807. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35808. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35809. };
  35810. /**
  35811. * Indicates that fresnel needs to be re-calculated for all submeshes
  35812. */
  35813. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35814. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35815. };
  35816. /**
  35817. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35818. */
  35819. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35820. this._markAllSubMeshesAsDirty(function (defines) {
  35821. defines.markAsFresnelDirty();
  35822. defines.markAsMiscDirty();
  35823. });
  35824. };
  35825. /**
  35826. * Indicates that lights need to be re-calculated for all submeshes
  35827. */
  35828. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35829. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35830. };
  35831. /**
  35832. * Indicates that attributes need to be re-calculated for all submeshes
  35833. */
  35834. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35835. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35836. };
  35837. /**
  35838. * Indicates that misc needs to be re-calculated for all submeshes
  35839. */
  35840. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35841. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35842. };
  35843. /**
  35844. * Indicates that textures and misc need to be re-calculated for all submeshes
  35845. */
  35846. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35847. this._markAllSubMeshesAsDirty(function (defines) {
  35848. defines.markAsTexturesDirty();
  35849. defines.markAsMiscDirty();
  35850. });
  35851. };
  35852. /**
  35853. * Disposes the material
  35854. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35855. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35856. */
  35857. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35858. // Animations
  35859. this.getScene().stopAnimation(this);
  35860. this.getScene().freeProcessedMaterials();
  35861. // Remove from scene
  35862. var index = this._scene.materials.indexOf(this);
  35863. if (index >= 0) {
  35864. this._scene.materials.splice(index, 1);
  35865. }
  35866. // Remove from meshes
  35867. for (index = 0; index < this._scene.meshes.length; index++) {
  35868. var mesh = this._scene.meshes[index];
  35869. if (mesh.material === this) {
  35870. mesh.material = null;
  35871. if (mesh.geometry) {
  35872. var geometry = (mesh.geometry);
  35873. if (this.storeEffectOnSubMeshes) {
  35874. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35875. var subMesh = _a[_i];
  35876. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35877. if (forceDisposeEffect && subMesh._materialEffect) {
  35878. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35879. }
  35880. }
  35881. }
  35882. else {
  35883. geometry._releaseVertexArrayObject(this._effect);
  35884. }
  35885. }
  35886. }
  35887. }
  35888. this._uniformBuffer.dispose();
  35889. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35890. if (forceDisposeEffect && this._effect) {
  35891. if (!this.storeEffectOnSubMeshes) {
  35892. this._scene.getEngine()._releaseEffect(this._effect);
  35893. }
  35894. this._effect = null;
  35895. }
  35896. // Callback
  35897. this.onDisposeObservable.notifyObservers(this);
  35898. this.onDisposeObservable.clear();
  35899. this.onBindObservable.clear();
  35900. this.onUnBindObservable.clear();
  35901. };
  35902. /**
  35903. * Serializes this material
  35904. * @returns the serialized material object
  35905. */
  35906. Material.prototype.serialize = function () {
  35907. return BABYLON.SerializationHelper.Serialize(this);
  35908. };
  35909. /**
  35910. * Creates a MultiMaterial from parsed MultiMaterial data.
  35911. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35912. * @param scene defines the hosting scene
  35913. * @returns a new MultiMaterial
  35914. */
  35915. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35916. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35917. multiMaterial.id = parsedMultiMaterial.id;
  35918. if (BABYLON.Tags) {
  35919. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35920. }
  35921. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35922. var subMatId = parsedMultiMaterial.materials[matIndex];
  35923. if (subMatId) {
  35924. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35925. }
  35926. else {
  35927. multiMaterial.subMaterials.push(null);
  35928. }
  35929. }
  35930. return multiMaterial;
  35931. };
  35932. /**
  35933. * Creates a material from parsed material data
  35934. * @param parsedMaterial defines parsed material data
  35935. * @param scene defines the hosting scene
  35936. * @param rootUrl defines the root URL to use to load textures
  35937. * @returns a new material
  35938. */
  35939. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35940. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35941. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35942. }
  35943. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35944. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35945. if (!BABYLON.LegacyPBRMaterial) {
  35946. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35947. return;
  35948. }
  35949. }
  35950. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35951. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35952. };
  35953. // Triangle views
  35954. Material._TriangleFillMode = 0;
  35955. Material._WireFrameFillMode = 1;
  35956. Material._PointFillMode = 2;
  35957. // Draw modes
  35958. Material._PointListDrawMode = 3;
  35959. Material._LineListDrawMode = 4;
  35960. Material._LineLoopDrawMode = 5;
  35961. Material._LineStripDrawMode = 6;
  35962. Material._TriangleStripDrawMode = 7;
  35963. Material._TriangleFanDrawMode = 8;
  35964. /**
  35965. * Stores the clock-wise side orientation
  35966. */
  35967. Material._ClockWiseSideOrientation = 0;
  35968. /**
  35969. * Stores the counter clock-wise side orientation
  35970. */
  35971. Material._CounterClockWiseSideOrientation = 1;
  35972. /**
  35973. * The dirty texture flag value
  35974. */
  35975. Material._TextureDirtyFlag = 1;
  35976. /**
  35977. * The dirty light flag value
  35978. */
  35979. Material._LightDirtyFlag = 2;
  35980. /**
  35981. * The dirty fresnel flag value
  35982. */
  35983. Material._FresnelDirtyFlag = 4;
  35984. /**
  35985. * The dirty attribute flag value
  35986. */
  35987. Material._AttributesDirtyFlag = 8;
  35988. /**
  35989. * The dirty misc flag value
  35990. */
  35991. Material._MiscDirtyFlag = 16;
  35992. __decorate([
  35993. BABYLON.serialize()
  35994. ], Material.prototype, "id", void 0);
  35995. __decorate([
  35996. BABYLON.serialize()
  35997. ], Material.prototype, "uniqueId", void 0);
  35998. __decorate([
  35999. BABYLON.serialize()
  36000. ], Material.prototype, "name", void 0);
  36001. __decorate([
  36002. BABYLON.serialize()
  36003. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  36004. __decorate([
  36005. BABYLON.serialize()
  36006. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  36007. __decorate([
  36008. BABYLON.serialize()
  36009. ], Material.prototype, "state", void 0);
  36010. __decorate([
  36011. BABYLON.serialize("alpha")
  36012. ], Material.prototype, "_alpha", void 0);
  36013. __decorate([
  36014. BABYLON.serialize("backFaceCulling")
  36015. ], Material.prototype, "_backFaceCulling", void 0);
  36016. __decorate([
  36017. BABYLON.serialize()
  36018. ], Material.prototype, "sideOrientation", void 0);
  36019. __decorate([
  36020. BABYLON.serialize("alphaMode")
  36021. ], Material.prototype, "_alphaMode", void 0);
  36022. __decorate([
  36023. BABYLON.serialize()
  36024. ], Material.prototype, "_needDepthPrePass", void 0);
  36025. __decorate([
  36026. BABYLON.serialize()
  36027. ], Material.prototype, "disableDepthWrite", void 0);
  36028. __decorate([
  36029. BABYLON.serialize()
  36030. ], Material.prototype, "forceDepthWrite", void 0);
  36031. __decorate([
  36032. BABYLON.serialize()
  36033. ], Material.prototype, "separateCullingPass", void 0);
  36034. __decorate([
  36035. BABYLON.serialize("fogEnabled")
  36036. ], Material.prototype, "_fogEnabled", void 0);
  36037. __decorate([
  36038. BABYLON.serialize()
  36039. ], Material.prototype, "pointSize", void 0);
  36040. __decorate([
  36041. BABYLON.serialize()
  36042. ], Material.prototype, "zOffset", void 0);
  36043. __decorate([
  36044. BABYLON.serialize()
  36045. ], Material.prototype, "wireframe", null);
  36046. __decorate([
  36047. BABYLON.serialize()
  36048. ], Material.prototype, "pointsCloud", null);
  36049. __decorate([
  36050. BABYLON.serialize()
  36051. ], Material.prototype, "fillMode", null);
  36052. return Material;
  36053. }());
  36054. BABYLON.Material = Material;
  36055. })(BABYLON || (BABYLON = {}));
  36056. //# sourceMappingURL=babylon.material.js.map
  36057. var BABYLON;
  36058. (function (BABYLON) {
  36059. var UniformBuffer = /** @class */ (function () {
  36060. /**
  36061. * Uniform buffer objects.
  36062. *
  36063. * Handles blocks of uniform on the GPU.
  36064. *
  36065. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36066. *
  36067. * For more information, please refer to :
  36068. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36069. */
  36070. function UniformBuffer(engine, data, dynamic) {
  36071. this._engine = engine;
  36072. this._noUBO = !engine.supportsUniformBuffers;
  36073. this._dynamic = dynamic;
  36074. this._data = data || [];
  36075. this._uniformLocations = {};
  36076. this._uniformSizes = {};
  36077. this._uniformLocationPointer = 0;
  36078. this._needSync = false;
  36079. if (this._noUBO) {
  36080. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36081. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36082. this.updateFloat = this._updateFloatForEffect;
  36083. this.updateFloat2 = this._updateFloat2ForEffect;
  36084. this.updateFloat3 = this._updateFloat3ForEffect;
  36085. this.updateFloat4 = this._updateFloat4ForEffect;
  36086. this.updateMatrix = this._updateMatrixForEffect;
  36087. this.updateVector3 = this._updateVector3ForEffect;
  36088. this.updateVector4 = this._updateVector4ForEffect;
  36089. this.updateColor3 = this._updateColor3ForEffect;
  36090. this.updateColor4 = this._updateColor4ForEffect;
  36091. }
  36092. else {
  36093. this._engine._uniformBuffers.push(this);
  36094. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36095. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36096. this.updateFloat = this._updateFloatForUniform;
  36097. this.updateFloat2 = this._updateFloat2ForUniform;
  36098. this.updateFloat3 = this._updateFloat3ForUniform;
  36099. this.updateFloat4 = this._updateFloat4ForUniform;
  36100. this.updateMatrix = this._updateMatrixForUniform;
  36101. this.updateVector3 = this._updateVector3ForUniform;
  36102. this.updateVector4 = this._updateVector4ForUniform;
  36103. this.updateColor3 = this._updateColor3ForUniform;
  36104. this.updateColor4 = this._updateColor4ForUniform;
  36105. }
  36106. }
  36107. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36108. // Properties
  36109. /**
  36110. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36111. * or just falling back on setUniformXXX calls.
  36112. */
  36113. get: function () {
  36114. return !this._noUBO;
  36115. },
  36116. enumerable: true,
  36117. configurable: true
  36118. });
  36119. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36120. /**
  36121. * Indicates if the WebGL underlying uniform buffer is in sync
  36122. * with the javascript cache data.
  36123. */
  36124. get: function () {
  36125. return !this._needSync;
  36126. },
  36127. enumerable: true,
  36128. configurable: true
  36129. });
  36130. /**
  36131. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36132. * Also, a dynamic UniformBuffer will disable cache verification and always
  36133. * update the underlying WebGL uniform buffer to the GPU.
  36134. */
  36135. UniformBuffer.prototype.isDynamic = function () {
  36136. return this._dynamic !== undefined;
  36137. };
  36138. /**
  36139. * The data cache on JS side.
  36140. */
  36141. UniformBuffer.prototype.getData = function () {
  36142. return this._bufferData;
  36143. };
  36144. /**
  36145. * The underlying WebGL Uniform buffer.
  36146. */
  36147. UniformBuffer.prototype.getBuffer = function () {
  36148. return this._buffer;
  36149. };
  36150. /**
  36151. * std140 layout specifies how to align data within an UBO structure.
  36152. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36153. * for specs.
  36154. */
  36155. UniformBuffer.prototype._fillAlignment = function (size) {
  36156. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36157. // and 4x4 matrices
  36158. // TODO : change if other types are used
  36159. var alignment;
  36160. if (size <= 2) {
  36161. alignment = size;
  36162. }
  36163. else {
  36164. alignment = 4;
  36165. }
  36166. if ((this._uniformLocationPointer % alignment) !== 0) {
  36167. var oldPointer = this._uniformLocationPointer;
  36168. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36169. var diff = this._uniformLocationPointer - oldPointer;
  36170. for (var i = 0; i < diff; i++) {
  36171. this._data.push(0);
  36172. }
  36173. }
  36174. };
  36175. /**
  36176. * Adds an uniform in the buffer.
  36177. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36178. * for the layout to be correct !
  36179. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36180. * @param {number|number[]} size Data size, or data directly.
  36181. */
  36182. UniformBuffer.prototype.addUniform = function (name, size) {
  36183. if (this._noUBO) {
  36184. return;
  36185. }
  36186. if (this._uniformLocations[name] !== undefined) {
  36187. // Already existing uniform
  36188. return;
  36189. }
  36190. // This function must be called in the order of the shader layout !
  36191. // size can be the size of the uniform, or data directly
  36192. var data;
  36193. if (size instanceof Array) {
  36194. data = size;
  36195. size = data.length;
  36196. }
  36197. else {
  36198. size = size;
  36199. data = [];
  36200. // Fill with zeros
  36201. for (var i = 0; i < size; i++) {
  36202. data.push(0);
  36203. }
  36204. }
  36205. this._fillAlignment(size);
  36206. this._uniformSizes[name] = size;
  36207. this._uniformLocations[name] = this._uniformLocationPointer;
  36208. this._uniformLocationPointer += size;
  36209. for (var i = 0; i < size; i++) {
  36210. this._data.push(data[i]);
  36211. }
  36212. this._needSync = true;
  36213. };
  36214. /**
  36215. * Wrapper for addUniform.
  36216. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36217. * @param {Matrix} mat A 4x4 matrix.
  36218. */
  36219. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36220. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36221. };
  36222. /**
  36223. * Wrapper for addUniform.
  36224. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36225. * @param {number} x
  36226. * @param {number} y
  36227. */
  36228. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36229. var temp = [x, y];
  36230. this.addUniform(name, temp);
  36231. };
  36232. /**
  36233. * Wrapper for addUniform.
  36234. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36235. * @param {number} x
  36236. * @param {number} y
  36237. * @param {number} z
  36238. */
  36239. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36240. var temp = [x, y, z];
  36241. this.addUniform(name, temp);
  36242. };
  36243. /**
  36244. * Wrapper for addUniform.
  36245. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36246. * @param {Color3} color
  36247. */
  36248. UniformBuffer.prototype.addColor3 = function (name, color) {
  36249. var temp = new Array();
  36250. color.toArray(temp);
  36251. this.addUniform(name, temp);
  36252. };
  36253. /**
  36254. * Wrapper for addUniform.
  36255. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36256. * @param {Color3} color
  36257. * @param {number} alpha
  36258. */
  36259. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36260. var temp = new Array();
  36261. color.toArray(temp);
  36262. temp.push(alpha);
  36263. this.addUniform(name, temp);
  36264. };
  36265. /**
  36266. * Wrapper for addUniform.
  36267. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36268. * @param {Vector3} vector
  36269. */
  36270. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36271. var temp = new Array();
  36272. vector.toArray(temp);
  36273. this.addUniform(name, temp);
  36274. };
  36275. /**
  36276. * Wrapper for addUniform.
  36277. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36278. */
  36279. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36280. this.addUniform(name, 12);
  36281. };
  36282. /**
  36283. * Wrapper for addUniform.
  36284. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36285. */
  36286. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36287. this.addUniform(name, 8);
  36288. };
  36289. /**
  36290. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36291. */
  36292. UniformBuffer.prototype.create = function () {
  36293. if (this._noUBO) {
  36294. return;
  36295. }
  36296. if (this._buffer) {
  36297. return; // nothing to do
  36298. }
  36299. // See spec, alignment must be filled as a vec4
  36300. this._fillAlignment(4);
  36301. this._bufferData = new Float32Array(this._data);
  36302. this._rebuild();
  36303. this._needSync = true;
  36304. };
  36305. UniformBuffer.prototype._rebuild = function () {
  36306. if (this._noUBO) {
  36307. return;
  36308. }
  36309. if (this._dynamic) {
  36310. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36311. }
  36312. else {
  36313. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36314. }
  36315. };
  36316. /**
  36317. * Updates the WebGL Uniform Buffer on the GPU.
  36318. * If the `dynamic` flag is set to true, no cache comparison is done.
  36319. * Otherwise, the buffer will be updated only if the cache differs.
  36320. */
  36321. UniformBuffer.prototype.update = function () {
  36322. if (!this._buffer) {
  36323. this.create();
  36324. return;
  36325. }
  36326. if (!this._dynamic && !this._needSync) {
  36327. return;
  36328. }
  36329. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36330. this._needSync = false;
  36331. };
  36332. /**
  36333. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36334. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36335. * @param {number[]|Float32Array} data Flattened data
  36336. * @param {number} size Size of the data.
  36337. */
  36338. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36339. var location = this._uniformLocations[uniformName];
  36340. if (location === undefined) {
  36341. if (this._buffer) {
  36342. // Cannot add an uniform if the buffer is already created
  36343. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36344. return;
  36345. }
  36346. this.addUniform(uniformName, size);
  36347. location = this._uniformLocations[uniformName];
  36348. }
  36349. if (!this._buffer) {
  36350. this.create();
  36351. }
  36352. if (!this._dynamic) {
  36353. // Cache for static uniform buffers
  36354. var changed = false;
  36355. for (var i = 0; i < size; i++) {
  36356. if (this._bufferData[location + i] !== data[i]) {
  36357. changed = true;
  36358. this._bufferData[location + i] = data[i];
  36359. }
  36360. }
  36361. this._needSync = this._needSync || changed;
  36362. }
  36363. else {
  36364. // No cache for dynamic
  36365. for (var i = 0; i < size; i++) {
  36366. this._bufferData[location + i] = data[i];
  36367. }
  36368. }
  36369. };
  36370. // Update methods
  36371. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36372. // To match std140, matrix must be realigned
  36373. for (var i = 0; i < 3; i++) {
  36374. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36375. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36376. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36377. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36378. }
  36379. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36380. };
  36381. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36382. this._currentEffect.setMatrix3x3(name, matrix);
  36383. };
  36384. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36385. this._currentEffect.setMatrix2x2(name, matrix);
  36386. };
  36387. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36388. // To match std140, matrix must be realigned
  36389. for (var i = 0; i < 2; i++) {
  36390. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36391. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36392. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36393. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36394. }
  36395. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36396. };
  36397. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36398. this._currentEffect.setFloat(name, x);
  36399. };
  36400. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36401. UniformBuffer._tempBuffer[0] = x;
  36402. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36403. };
  36404. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36405. if (suffix === void 0) { suffix = ""; }
  36406. this._currentEffect.setFloat2(name + suffix, x, y);
  36407. };
  36408. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36409. if (suffix === void 0) { suffix = ""; }
  36410. UniformBuffer._tempBuffer[0] = x;
  36411. UniformBuffer._tempBuffer[1] = y;
  36412. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36413. };
  36414. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36415. if (suffix === void 0) { suffix = ""; }
  36416. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36417. };
  36418. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36419. if (suffix === void 0) { suffix = ""; }
  36420. UniformBuffer._tempBuffer[0] = x;
  36421. UniformBuffer._tempBuffer[1] = y;
  36422. UniformBuffer._tempBuffer[2] = z;
  36423. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36424. };
  36425. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36426. if (suffix === void 0) { suffix = ""; }
  36427. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36428. };
  36429. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36430. if (suffix === void 0) { suffix = ""; }
  36431. UniformBuffer._tempBuffer[0] = x;
  36432. UniformBuffer._tempBuffer[1] = y;
  36433. UniformBuffer._tempBuffer[2] = z;
  36434. UniformBuffer._tempBuffer[3] = w;
  36435. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36436. };
  36437. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36438. this._currentEffect.setMatrix(name, mat);
  36439. };
  36440. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36441. this.updateUniform(name, mat.toArray(), 16);
  36442. };
  36443. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36444. this._currentEffect.setVector3(name, vector);
  36445. };
  36446. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36447. vector.toArray(UniformBuffer._tempBuffer);
  36448. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36449. };
  36450. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36451. this._currentEffect.setVector4(name, vector);
  36452. };
  36453. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36454. vector.toArray(UniformBuffer._tempBuffer);
  36455. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36456. };
  36457. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36458. if (suffix === void 0) { suffix = ""; }
  36459. this._currentEffect.setColor3(name + suffix, color);
  36460. };
  36461. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36462. if (suffix === void 0) { suffix = ""; }
  36463. color.toArray(UniformBuffer._tempBuffer);
  36464. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36465. };
  36466. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36467. if (suffix === void 0) { suffix = ""; }
  36468. this._currentEffect.setColor4(name + suffix, color, alpha);
  36469. };
  36470. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36471. if (suffix === void 0) { suffix = ""; }
  36472. color.toArray(UniformBuffer._tempBuffer);
  36473. UniformBuffer._tempBuffer[3] = alpha;
  36474. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36475. };
  36476. /**
  36477. * Sets a sampler uniform on the effect.
  36478. * @param {string} name Name of the sampler.
  36479. * @param {Texture} texture
  36480. */
  36481. UniformBuffer.prototype.setTexture = function (name, texture) {
  36482. this._currentEffect.setTexture(name, texture);
  36483. };
  36484. /**
  36485. * Directly updates the value of the uniform in the cache AND on the GPU.
  36486. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36487. * @param {number[]|Float32Array} data Flattened data
  36488. */
  36489. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36490. this.updateUniform(uniformName, data, data.length);
  36491. this.update();
  36492. };
  36493. /**
  36494. * Binds this uniform buffer to an effect.
  36495. * @param {Effect} effect
  36496. * @param {string} name Name of the uniform block in the shader.
  36497. */
  36498. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36499. this._currentEffect = effect;
  36500. if (this._noUBO || !this._buffer) {
  36501. return;
  36502. }
  36503. effect.bindUniformBuffer(this._buffer, name);
  36504. };
  36505. /**
  36506. * Disposes the uniform buffer.
  36507. */
  36508. UniformBuffer.prototype.dispose = function () {
  36509. if (this._noUBO) {
  36510. return;
  36511. }
  36512. var index = this._engine._uniformBuffers.indexOf(this);
  36513. if (index !== -1) {
  36514. this._engine._uniformBuffers.splice(index, 1);
  36515. }
  36516. if (!this._buffer) {
  36517. return;
  36518. }
  36519. if (this._engine._releaseBuffer(this._buffer)) {
  36520. this._buffer = null;
  36521. }
  36522. };
  36523. // Pool for avoiding memory leaks
  36524. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36525. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36526. return UniformBuffer;
  36527. }());
  36528. BABYLON.UniformBuffer = UniformBuffer;
  36529. })(BABYLON || (BABYLON = {}));
  36530. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36531. var BABYLON;
  36532. (function (BABYLON) {
  36533. /**
  36534. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36535. */
  36536. var VertexData = /** @class */ (function () {
  36537. function VertexData() {
  36538. }
  36539. /**
  36540. * Uses the passed data array to set the set the values for the specified kind of data
  36541. * @param data a linear array of floating numbers
  36542. * @param kind the type of data that is being set, eg positions, colors etc
  36543. */
  36544. VertexData.prototype.set = function (data, kind) {
  36545. switch (kind) {
  36546. case BABYLON.VertexBuffer.PositionKind:
  36547. this.positions = data;
  36548. break;
  36549. case BABYLON.VertexBuffer.NormalKind:
  36550. this.normals = data;
  36551. break;
  36552. case BABYLON.VertexBuffer.TangentKind:
  36553. this.tangents = data;
  36554. break;
  36555. case BABYLON.VertexBuffer.UVKind:
  36556. this.uvs = data;
  36557. break;
  36558. case BABYLON.VertexBuffer.UV2Kind:
  36559. this.uvs2 = data;
  36560. break;
  36561. case BABYLON.VertexBuffer.UV3Kind:
  36562. this.uvs3 = data;
  36563. break;
  36564. case BABYLON.VertexBuffer.UV4Kind:
  36565. this.uvs4 = data;
  36566. break;
  36567. case BABYLON.VertexBuffer.UV5Kind:
  36568. this.uvs5 = data;
  36569. break;
  36570. case BABYLON.VertexBuffer.UV6Kind:
  36571. this.uvs6 = data;
  36572. break;
  36573. case BABYLON.VertexBuffer.ColorKind:
  36574. this.colors = data;
  36575. break;
  36576. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36577. this.matricesIndices = data;
  36578. break;
  36579. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36580. this.matricesWeights = data;
  36581. break;
  36582. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36583. this.matricesIndicesExtra = data;
  36584. break;
  36585. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36586. this.matricesWeightsExtra = data;
  36587. break;
  36588. }
  36589. };
  36590. /**
  36591. * Associates the vertexData to the passed Mesh.
  36592. * Sets it as updatable or not (default `false`)
  36593. * @param mesh the mesh the vertexData is applied to
  36594. * @param updatable when used and having the value true allows new data to update the vertexData
  36595. * @returns the VertexData
  36596. */
  36597. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36598. this._applyTo(mesh, updatable);
  36599. return this;
  36600. };
  36601. /**
  36602. * Associates the vertexData to the passed Geometry.
  36603. * Sets it as updatable or not (default `false`)
  36604. * @param geometry the geometry the vertexData is applied to
  36605. * @param updatable when used and having the value true allows new data to update the vertexData
  36606. * @returns VertexData
  36607. */
  36608. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36609. this._applyTo(geometry, updatable);
  36610. return this;
  36611. };
  36612. /**
  36613. * Updates the associated mesh
  36614. * @param mesh the mesh to be updated
  36615. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36616. * @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
  36617. * @returns VertexData
  36618. */
  36619. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36620. this._update(mesh);
  36621. return this;
  36622. };
  36623. /**
  36624. * Updates the associated geometry
  36625. * @param geometry the geometry to be updated
  36626. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36627. * @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
  36628. * @returns VertexData.
  36629. */
  36630. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36631. this._update(geometry);
  36632. return this;
  36633. };
  36634. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36635. if (updatable === void 0) { updatable = false; }
  36636. if (this.positions) {
  36637. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36638. }
  36639. if (this.normals) {
  36640. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36641. }
  36642. if (this.tangents) {
  36643. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36644. }
  36645. if (this.uvs) {
  36646. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36647. }
  36648. if (this.uvs2) {
  36649. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36650. }
  36651. if (this.uvs3) {
  36652. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36653. }
  36654. if (this.uvs4) {
  36655. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36656. }
  36657. if (this.uvs5) {
  36658. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36659. }
  36660. if (this.uvs6) {
  36661. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36662. }
  36663. if (this.colors) {
  36664. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36665. }
  36666. if (this.matricesIndices) {
  36667. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36668. }
  36669. if (this.matricesWeights) {
  36670. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36671. }
  36672. if (this.matricesIndicesExtra) {
  36673. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36674. }
  36675. if (this.matricesWeightsExtra) {
  36676. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36677. }
  36678. if (this.indices) {
  36679. meshOrGeometry.setIndices(this.indices, null, updatable);
  36680. }
  36681. else {
  36682. meshOrGeometry.setIndices([], null);
  36683. }
  36684. return this;
  36685. };
  36686. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36687. if (this.positions) {
  36688. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36689. }
  36690. if (this.normals) {
  36691. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36692. }
  36693. if (this.tangents) {
  36694. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36695. }
  36696. if (this.uvs) {
  36697. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36698. }
  36699. if (this.uvs2) {
  36700. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36701. }
  36702. if (this.uvs3) {
  36703. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36704. }
  36705. if (this.uvs4) {
  36706. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36707. }
  36708. if (this.uvs5) {
  36709. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36710. }
  36711. if (this.uvs6) {
  36712. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36713. }
  36714. if (this.colors) {
  36715. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36716. }
  36717. if (this.matricesIndices) {
  36718. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36719. }
  36720. if (this.matricesWeights) {
  36721. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36722. }
  36723. if (this.matricesIndicesExtra) {
  36724. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36725. }
  36726. if (this.matricesWeightsExtra) {
  36727. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36728. }
  36729. if (this.indices) {
  36730. meshOrGeometry.setIndices(this.indices, null);
  36731. }
  36732. return this;
  36733. };
  36734. /**
  36735. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36736. * @param matrix the transforming matrix
  36737. * @returns the VertexData
  36738. */
  36739. VertexData.prototype.transform = function (matrix) {
  36740. var transformed = BABYLON.Vector3.Zero();
  36741. var index;
  36742. if (this.positions) {
  36743. var position = BABYLON.Vector3.Zero();
  36744. for (index = 0; index < this.positions.length; index += 3) {
  36745. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36746. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36747. this.positions[index] = transformed.x;
  36748. this.positions[index + 1] = transformed.y;
  36749. this.positions[index + 2] = transformed.z;
  36750. }
  36751. }
  36752. if (this.normals) {
  36753. var normal = BABYLON.Vector3.Zero();
  36754. for (index = 0; index < this.normals.length; index += 3) {
  36755. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36756. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36757. this.normals[index] = transformed.x;
  36758. this.normals[index + 1] = transformed.y;
  36759. this.normals[index + 2] = transformed.z;
  36760. }
  36761. }
  36762. if (this.tangents) {
  36763. var tangent = BABYLON.Vector4.Zero();
  36764. var tangentTransformed = BABYLON.Vector4.Zero();
  36765. for (index = 0; index < this.tangents.length; index += 4) {
  36766. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36767. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36768. this.tangents[index] = tangentTransformed.x;
  36769. this.tangents[index + 1] = tangentTransformed.y;
  36770. this.tangents[index + 2] = tangentTransformed.z;
  36771. this.tangents[index + 3] = tangentTransformed.w;
  36772. }
  36773. }
  36774. return this;
  36775. };
  36776. /**
  36777. * Merges the passed VertexData into the current one
  36778. * @param other the VertexData to be merged into the current one
  36779. * @returns the modified VertexData
  36780. */
  36781. VertexData.prototype.merge = function (other) {
  36782. this._validate();
  36783. other._validate();
  36784. if (!this.normals !== !other.normals ||
  36785. !this.tangents !== !other.tangents ||
  36786. !this.uvs !== !other.uvs ||
  36787. !this.uvs2 !== !other.uvs2 ||
  36788. !this.uvs3 !== !other.uvs3 ||
  36789. !this.uvs4 !== !other.uvs4 ||
  36790. !this.uvs5 !== !other.uvs5 ||
  36791. !this.uvs6 !== !other.uvs6 ||
  36792. !this.colors !== !other.colors ||
  36793. !this.matricesIndices !== !other.matricesIndices ||
  36794. !this.matricesWeights !== !other.matricesWeights ||
  36795. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36796. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36797. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36798. }
  36799. if (other.indices) {
  36800. if (!this.indices) {
  36801. this.indices = [];
  36802. }
  36803. var offset = this.positions ? this.positions.length / 3 : 0;
  36804. for (var index = 0; index < other.indices.length; index++) {
  36805. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36806. this.indices.push(other.indices[index] + offset);
  36807. }
  36808. }
  36809. this.positions = this._mergeElement(this.positions, other.positions);
  36810. this.normals = this._mergeElement(this.normals, other.normals);
  36811. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36812. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36813. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36814. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36815. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36816. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36817. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36818. this.colors = this._mergeElement(this.colors, other.colors);
  36819. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36820. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36821. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36822. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36823. return this;
  36824. };
  36825. VertexData.prototype._mergeElement = function (source, other) {
  36826. if (!source) {
  36827. return other;
  36828. }
  36829. if (!other) {
  36830. return source;
  36831. }
  36832. var len = other.length + source.length;
  36833. var isSrcTypedArray = source instanceof Float32Array;
  36834. var isOthTypedArray = other instanceof Float32Array;
  36835. // use non-loop method when the source is Float32Array
  36836. if (isSrcTypedArray) {
  36837. var ret32 = new Float32Array(len);
  36838. ret32.set(source);
  36839. ret32.set(other, source.length);
  36840. return ret32;
  36841. // source is number[], when other is also use concat
  36842. }
  36843. else if (!isOthTypedArray) {
  36844. return source.concat(other);
  36845. // source is a number[], but other is a Float32Array, loop required
  36846. }
  36847. else {
  36848. var ret = source.slice(0); // copy source to a separate array
  36849. for (var i = 0, len = other.length; i < len; i++) {
  36850. ret.push(other[i]);
  36851. }
  36852. return ret;
  36853. }
  36854. };
  36855. VertexData.prototype._validate = function () {
  36856. if (!this.positions) {
  36857. throw new Error("Positions are required");
  36858. }
  36859. var getElementCount = function (kind, values) {
  36860. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36861. if ((values.length % stride) !== 0) {
  36862. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36863. }
  36864. return values.length / stride;
  36865. };
  36866. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36867. var validateElementCount = function (kind, values) {
  36868. var elementCount = getElementCount(kind, values);
  36869. if (elementCount !== positionsElementCount) {
  36870. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36871. }
  36872. };
  36873. if (this.normals)
  36874. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36875. if (this.tangents)
  36876. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36877. if (this.uvs)
  36878. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36879. if (this.uvs2)
  36880. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36881. if (this.uvs3)
  36882. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36883. if (this.uvs4)
  36884. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36885. if (this.uvs5)
  36886. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36887. if (this.uvs6)
  36888. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36889. if (this.colors)
  36890. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36891. if (this.matricesIndices)
  36892. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36893. if (this.matricesWeights)
  36894. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36895. if (this.matricesIndicesExtra)
  36896. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36897. if (this.matricesWeightsExtra)
  36898. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36899. };
  36900. /**
  36901. * Serializes the VertexData
  36902. * @returns a serialized object
  36903. */
  36904. VertexData.prototype.serialize = function () {
  36905. var serializationObject = this.serialize();
  36906. if (this.positions) {
  36907. serializationObject.positions = this.positions;
  36908. }
  36909. if (this.normals) {
  36910. serializationObject.normals = this.normals;
  36911. }
  36912. if (this.tangents) {
  36913. serializationObject.tangents = this.tangents;
  36914. }
  36915. if (this.uvs) {
  36916. serializationObject.uvs = this.uvs;
  36917. }
  36918. if (this.uvs2) {
  36919. serializationObject.uvs2 = this.uvs2;
  36920. }
  36921. if (this.uvs3) {
  36922. serializationObject.uvs3 = this.uvs3;
  36923. }
  36924. if (this.uvs4) {
  36925. serializationObject.uvs4 = this.uvs4;
  36926. }
  36927. if (this.uvs5) {
  36928. serializationObject.uvs5 = this.uvs5;
  36929. }
  36930. if (this.uvs6) {
  36931. serializationObject.uvs6 = this.uvs6;
  36932. }
  36933. if (this.colors) {
  36934. serializationObject.colors = this.colors;
  36935. }
  36936. if (this.matricesIndices) {
  36937. serializationObject.matricesIndices = this.matricesIndices;
  36938. serializationObject.matricesIndices._isExpanded = true;
  36939. }
  36940. if (this.matricesWeights) {
  36941. serializationObject.matricesWeights = this.matricesWeights;
  36942. }
  36943. if (this.matricesIndicesExtra) {
  36944. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36945. serializationObject.matricesIndicesExtra._isExpanded = true;
  36946. }
  36947. if (this.matricesWeightsExtra) {
  36948. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36949. }
  36950. serializationObject.indices = this.indices;
  36951. return serializationObject;
  36952. };
  36953. // Statics
  36954. /**
  36955. * Extracts the vertexData from a mesh
  36956. * @param mesh the mesh from which to extract the VertexData
  36957. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36958. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36959. * @returns the object VertexData associated to the passed mesh
  36960. */
  36961. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36962. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36963. };
  36964. /**
  36965. * Extracts the vertexData from the geometry
  36966. * @param geometry the geometry from which to extract the VertexData
  36967. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36968. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36969. * @returns the object VertexData associated to the passed mesh
  36970. */
  36971. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36972. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36973. };
  36974. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36975. var result = new VertexData();
  36976. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36977. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36978. }
  36979. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36980. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36981. }
  36982. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36983. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36984. }
  36985. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36986. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36987. }
  36988. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36989. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36990. }
  36991. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36992. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36993. }
  36994. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36995. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36996. }
  36997. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36998. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36999. }
  37000. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37001. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  37002. }
  37003. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37004. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  37005. }
  37006. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37007. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  37008. }
  37009. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37010. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  37011. }
  37012. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  37013. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  37014. }
  37015. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  37016. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  37017. }
  37018. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  37019. return result;
  37020. };
  37021. /**
  37022. * Creates the VertexData for a Ribbon
  37023. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  37024. * * pathArray array of paths, each of which an array of successive Vector3
  37025. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  37026. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  37027. * * 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
  37028. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37029. * * 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)
  37030. * * 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)
  37031. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  37032. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  37033. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  37034. * @returns the VertexData of the ribbon
  37035. */
  37036. VertexData.CreateRibbon = function (options) {
  37037. var pathArray = options.pathArray;
  37038. var closeArray = options.closeArray || false;
  37039. var closePath = options.closePath || false;
  37040. var invertUV = options.invertUV || false;
  37041. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37042. var offset = options.offset || defaultOffset;
  37043. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37044. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37045. var customUV = options.uvs;
  37046. var customColors = options.colors;
  37047. var positions = [];
  37048. var indices = [];
  37049. var normals = [];
  37050. var uvs = [];
  37051. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37052. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37053. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37054. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37055. var minlg; // minimal length among all paths from pathArray
  37056. var lg = []; // array of path lengths : nb of vertex per path
  37057. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37058. var p; // path iterator
  37059. var i; // point iterator
  37060. var j; // point iterator
  37061. // if single path in pathArray
  37062. if (pathArray.length < 2) {
  37063. var ar1 = [];
  37064. var ar2 = [];
  37065. for (i = 0; i < pathArray[0].length - offset; i++) {
  37066. ar1.push(pathArray[0][i]);
  37067. ar2.push(pathArray[0][i + offset]);
  37068. }
  37069. pathArray = [ar1, ar2];
  37070. }
  37071. // positions and horizontal distances (u)
  37072. var idc = 0;
  37073. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37074. var path;
  37075. var l;
  37076. minlg = pathArray[0].length;
  37077. var vectlg;
  37078. var dist;
  37079. for (p = 0; p < pathArray.length; p++) {
  37080. uTotalDistance[p] = 0;
  37081. us[p] = [0];
  37082. path = pathArray[p];
  37083. l = path.length;
  37084. minlg = (minlg < l) ? minlg : l;
  37085. j = 0;
  37086. while (j < l) {
  37087. positions.push(path[j].x, path[j].y, path[j].z);
  37088. if (j > 0) {
  37089. vectlg = path[j].subtract(path[j - 1]).length();
  37090. dist = vectlg + uTotalDistance[p];
  37091. us[p].push(dist);
  37092. uTotalDistance[p] = dist;
  37093. }
  37094. j++;
  37095. }
  37096. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37097. j--;
  37098. positions.push(path[0].x, path[0].y, path[0].z);
  37099. vectlg = path[j].subtract(path[0]).length();
  37100. dist = vectlg + uTotalDistance[p];
  37101. us[p].push(dist);
  37102. uTotalDistance[p] = dist;
  37103. }
  37104. lg[p] = l + closePathCorr;
  37105. idx[p] = idc;
  37106. idc += (l + closePathCorr);
  37107. }
  37108. // vertical distances (v)
  37109. var path1;
  37110. var path2;
  37111. var vertex1 = null;
  37112. var vertex2 = null;
  37113. for (i = 0; i < minlg + closePathCorr; i++) {
  37114. vTotalDistance[i] = 0;
  37115. vs[i] = [0];
  37116. for (p = 0; p < pathArray.length - 1; p++) {
  37117. path1 = pathArray[p];
  37118. path2 = pathArray[p + 1];
  37119. if (i === minlg) { // closePath
  37120. vertex1 = path1[0];
  37121. vertex2 = path2[0];
  37122. }
  37123. else {
  37124. vertex1 = path1[i];
  37125. vertex2 = path2[i];
  37126. }
  37127. vectlg = vertex2.subtract(vertex1).length();
  37128. dist = vectlg + vTotalDistance[i];
  37129. vs[i].push(dist);
  37130. vTotalDistance[i] = dist;
  37131. }
  37132. if (closeArray && vertex2 && vertex1) {
  37133. path1 = pathArray[p];
  37134. path2 = pathArray[0];
  37135. if (i === minlg) { // closePath
  37136. vertex2 = path2[0];
  37137. }
  37138. vectlg = vertex2.subtract(vertex1).length();
  37139. dist = vectlg + vTotalDistance[i];
  37140. vTotalDistance[i] = dist;
  37141. }
  37142. }
  37143. // uvs
  37144. var u;
  37145. var v;
  37146. if (customUV) {
  37147. for (p = 0; p < customUV.length; p++) {
  37148. uvs.push(customUV[p].x, customUV[p].y);
  37149. }
  37150. }
  37151. else {
  37152. for (p = 0; p < pathArray.length; p++) {
  37153. for (i = 0; i < minlg + closePathCorr; i++) {
  37154. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37155. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37156. if (invertUV) {
  37157. uvs.push(v, u);
  37158. }
  37159. else {
  37160. uvs.push(u, v);
  37161. }
  37162. }
  37163. }
  37164. }
  37165. // indices
  37166. p = 0; // path index
  37167. var pi = 0; // positions array index
  37168. var l1 = lg[p] - 1; // path1 length
  37169. var l2 = lg[p + 1] - 1; // path2 length
  37170. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37171. var shft = idx[1] - idx[0]; // shift
  37172. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37173. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37174. // 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
  37175. indices.push(pi, pi + shft, pi + 1);
  37176. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37177. pi += 1;
  37178. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37179. p++;
  37180. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37181. shft = idx[0] - idx[p];
  37182. l1 = lg[p] - 1;
  37183. l2 = lg[0] - 1;
  37184. }
  37185. else {
  37186. shft = idx[p + 1] - idx[p];
  37187. l1 = lg[p] - 1;
  37188. l2 = lg[p + 1] - 1;
  37189. }
  37190. pi = idx[p];
  37191. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37192. }
  37193. }
  37194. // normals
  37195. VertexData.ComputeNormals(positions, indices, normals);
  37196. if (closePath) { // update both the first and last vertex normals to their average value
  37197. var indexFirst = 0;
  37198. var indexLast = 0;
  37199. for (p = 0; p < pathArray.length; p++) {
  37200. indexFirst = idx[p] * 3;
  37201. if (p + 1 < pathArray.length) {
  37202. indexLast = (idx[p + 1] - 1) * 3;
  37203. }
  37204. else {
  37205. indexLast = normals.length - 3;
  37206. }
  37207. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37208. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37209. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37210. normals[indexLast] = normals[indexFirst];
  37211. normals[indexLast + 1] = normals[indexFirst + 1];
  37212. normals[indexLast + 2] = normals[indexFirst + 2];
  37213. }
  37214. }
  37215. // sides
  37216. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37217. // Colors
  37218. var colors = null;
  37219. if (customColors) {
  37220. colors = new Float32Array(customColors.length * 4);
  37221. for (var c = 0; c < customColors.length; c++) {
  37222. colors[c * 4] = customColors[c].r;
  37223. colors[c * 4 + 1] = customColors[c].g;
  37224. colors[c * 4 + 2] = customColors[c].b;
  37225. colors[c * 4 + 3] = customColors[c].a;
  37226. }
  37227. }
  37228. // Result
  37229. var vertexData = new VertexData();
  37230. var positions32 = new Float32Array(positions);
  37231. var normals32 = new Float32Array(normals);
  37232. var uvs32 = new Float32Array(uvs);
  37233. vertexData.indices = indices;
  37234. vertexData.positions = positions32;
  37235. vertexData.normals = normals32;
  37236. vertexData.uvs = uvs32;
  37237. if (colors) {
  37238. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37239. }
  37240. if (closePath) {
  37241. vertexData._idx = idx;
  37242. }
  37243. return vertexData;
  37244. };
  37245. /**
  37246. * Creates the VertexData for a box
  37247. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37248. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37249. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37250. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37251. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37252. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37253. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37254. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37255. * * 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)
  37256. * * 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)
  37257. * @returns the VertexData of the box
  37258. */
  37259. VertexData.CreateBox = function (options) {
  37260. var normalsSource = [
  37261. new BABYLON.Vector3(0, 0, 1),
  37262. new BABYLON.Vector3(0, 0, -1),
  37263. new BABYLON.Vector3(1, 0, 0),
  37264. new BABYLON.Vector3(-1, 0, 0),
  37265. new BABYLON.Vector3(0, 1, 0),
  37266. new BABYLON.Vector3(0, -1, 0)
  37267. ];
  37268. var indices = [];
  37269. var positions = [];
  37270. var normals = [];
  37271. var uvs = [];
  37272. var width = options.width || options.size || 1;
  37273. var height = options.height || options.size || 1;
  37274. var depth = options.depth || options.size || 1;
  37275. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37276. var faceUV = options.faceUV || new Array(6);
  37277. var faceColors = options.faceColors;
  37278. var colors = [];
  37279. // default face colors and UV if undefined
  37280. for (var f = 0; f < 6; f++) {
  37281. if (faceUV[f] === undefined) {
  37282. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37283. }
  37284. if (faceColors && faceColors[f] === undefined) {
  37285. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37286. }
  37287. }
  37288. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37289. // Create each face in turn.
  37290. for (var index = 0; index < normalsSource.length; index++) {
  37291. var normal = normalsSource[index];
  37292. // Get two vectors perpendicular to the face normal and to each other.
  37293. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37294. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37295. // Six indices (two triangles) per face.
  37296. var verticesLength = positions.length / 3;
  37297. indices.push(verticesLength);
  37298. indices.push(verticesLength + 1);
  37299. indices.push(verticesLength + 2);
  37300. indices.push(verticesLength);
  37301. indices.push(verticesLength + 2);
  37302. indices.push(verticesLength + 3);
  37303. // Four vertices per face.
  37304. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37305. positions.push(vertex.x, vertex.y, vertex.z);
  37306. normals.push(normal.x, normal.y, normal.z);
  37307. uvs.push(faceUV[index].z, faceUV[index].w);
  37308. if (faceColors) {
  37309. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37310. }
  37311. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37312. positions.push(vertex.x, vertex.y, vertex.z);
  37313. normals.push(normal.x, normal.y, normal.z);
  37314. uvs.push(faceUV[index].x, faceUV[index].w);
  37315. if (faceColors) {
  37316. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37317. }
  37318. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37319. positions.push(vertex.x, vertex.y, vertex.z);
  37320. normals.push(normal.x, normal.y, normal.z);
  37321. uvs.push(faceUV[index].x, faceUV[index].y);
  37322. if (faceColors) {
  37323. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37324. }
  37325. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37326. positions.push(vertex.x, vertex.y, vertex.z);
  37327. normals.push(normal.x, normal.y, normal.z);
  37328. uvs.push(faceUV[index].z, faceUV[index].y);
  37329. if (faceColors) {
  37330. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37331. }
  37332. }
  37333. // sides
  37334. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37335. // Result
  37336. var vertexData = new VertexData();
  37337. vertexData.indices = indices;
  37338. vertexData.positions = positions;
  37339. vertexData.normals = normals;
  37340. vertexData.uvs = uvs;
  37341. if (faceColors) {
  37342. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37343. vertexData.colors = totalColors;
  37344. }
  37345. return vertexData;
  37346. };
  37347. /**
  37348. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37349. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37350. * * segments sets the number of horizontal strips optional, default 32
  37351. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37352. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37353. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37354. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37355. * * 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
  37356. * * 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
  37357. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37358. * * 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)
  37359. * * 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)
  37360. * @returns the VertexData of the ellipsoid
  37361. */
  37362. VertexData.CreateSphere = function (options) {
  37363. var segments = options.segments || 32;
  37364. var diameterX = options.diameterX || options.diameter || 1;
  37365. var diameterY = options.diameterY || options.diameter || 1;
  37366. var diameterZ = options.diameterZ || options.diameter || 1;
  37367. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37368. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37369. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37370. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37371. var totalZRotationSteps = 2 + segments;
  37372. var totalYRotationSteps = 2 * totalZRotationSteps;
  37373. var indices = [];
  37374. var positions = [];
  37375. var normals = [];
  37376. var uvs = [];
  37377. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37378. var normalizedZ = zRotationStep / totalZRotationSteps;
  37379. var angleZ = normalizedZ * Math.PI * slice;
  37380. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37381. var normalizedY = yRotationStep / totalYRotationSteps;
  37382. var angleY = normalizedY * Math.PI * 2 * arc;
  37383. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37384. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37385. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37386. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37387. var vertex = complete.multiply(radius);
  37388. var normal = complete.divide(radius).normalize();
  37389. positions.push(vertex.x, vertex.y, vertex.z);
  37390. normals.push(normal.x, normal.y, normal.z);
  37391. uvs.push(normalizedY, normalizedZ);
  37392. }
  37393. if (zRotationStep > 0) {
  37394. var verticesCount = positions.length / 3;
  37395. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37396. indices.push((firstIndex));
  37397. indices.push((firstIndex + 1));
  37398. indices.push(firstIndex + totalYRotationSteps + 1);
  37399. indices.push((firstIndex + totalYRotationSteps + 1));
  37400. indices.push((firstIndex + 1));
  37401. indices.push((firstIndex + totalYRotationSteps + 2));
  37402. }
  37403. }
  37404. }
  37405. // Sides
  37406. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37407. // Result
  37408. var vertexData = new VertexData();
  37409. vertexData.indices = indices;
  37410. vertexData.positions = positions;
  37411. vertexData.normals = normals;
  37412. vertexData.uvs = uvs;
  37413. return vertexData;
  37414. };
  37415. /**
  37416. * Creates the VertexData for a cylinder, cone or prism
  37417. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37418. * * height sets the height (y direction) of the cylinder, optional, default 2
  37419. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37420. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37421. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37422. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37423. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37424. * * 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
  37425. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37426. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37427. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37428. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37429. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37430. * * 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)
  37431. * * 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)
  37432. * @returns the VertexData of the cylinder, cone or prism
  37433. */
  37434. VertexData.CreateCylinder = function (options) {
  37435. var height = options.height || 2;
  37436. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37437. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37438. var tessellation = options.tessellation || 24;
  37439. var subdivisions = options.subdivisions || 1;
  37440. var hasRings = options.hasRings ? true : false;
  37441. var enclose = options.enclose ? true : false;
  37442. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37443. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37444. var faceUV = options.faceUV || new Array(3);
  37445. var faceColors = options.faceColors;
  37446. // default face colors and UV if undefined
  37447. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37448. var ringNb = (hasRings) ? subdivisions : 1;
  37449. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37450. var f;
  37451. for (f = 0; f < surfaceNb; f++) {
  37452. if (faceColors && faceColors[f] === undefined) {
  37453. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37454. }
  37455. }
  37456. for (f = 0; f < surfaceNb; f++) {
  37457. if (faceUV && faceUV[f] === undefined) {
  37458. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37459. }
  37460. }
  37461. var indices = new Array();
  37462. var positions = new Array();
  37463. var normals = new Array();
  37464. var uvs = new Array();
  37465. var colors = new Array();
  37466. var angle_step = Math.PI * 2 * arc / tessellation;
  37467. var angle;
  37468. var h;
  37469. var radius;
  37470. var tan = (diameterBottom - diameterTop) / 2 / height;
  37471. var ringVertex = BABYLON.Vector3.Zero();
  37472. var ringNormal = BABYLON.Vector3.Zero();
  37473. var ringFirstVertex = BABYLON.Vector3.Zero();
  37474. var ringFirstNormal = BABYLON.Vector3.Zero();
  37475. var quadNormal = BABYLON.Vector3.Zero();
  37476. var Y = BABYLON.Axis.Y;
  37477. // positions, normals, uvs
  37478. var i;
  37479. var j;
  37480. var r;
  37481. var ringIdx = 1;
  37482. var s = 1; // surface index
  37483. var cs = 0;
  37484. var v = 0;
  37485. for (i = 0; i <= subdivisions; i++) {
  37486. h = i / subdivisions;
  37487. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37488. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37489. for (r = 0; r < ringIdx; r++) {
  37490. if (hasRings) {
  37491. s += r;
  37492. }
  37493. if (enclose) {
  37494. s += 2 * r;
  37495. }
  37496. for (j = 0; j <= tessellation; j++) {
  37497. angle = j * angle_step;
  37498. // position
  37499. ringVertex.x = Math.cos(-angle) * radius;
  37500. ringVertex.y = -height / 2 + h * height;
  37501. ringVertex.z = Math.sin(-angle) * radius;
  37502. // normal
  37503. if (diameterTop === 0 && i === subdivisions) {
  37504. // if no top cap, reuse former normals
  37505. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37506. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37507. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37508. }
  37509. else {
  37510. ringNormal.x = ringVertex.x;
  37511. ringNormal.z = ringVertex.z;
  37512. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37513. ringNormal.normalize();
  37514. }
  37515. // keep first ring vertex values for enclose
  37516. if (j === 0) {
  37517. ringFirstVertex.copyFrom(ringVertex);
  37518. ringFirstNormal.copyFrom(ringNormal);
  37519. }
  37520. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37521. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37522. if (hasRings) {
  37523. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37524. }
  37525. else {
  37526. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37527. }
  37528. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37529. if (faceColors) {
  37530. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37531. }
  37532. }
  37533. // if enclose, add four vertices and their dedicated normals
  37534. if (arc !== 1 && enclose) {
  37535. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37536. positions.push(0, ringVertex.y, 0);
  37537. positions.push(0, ringVertex.y, 0);
  37538. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37539. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37540. quadNormal.normalize();
  37541. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37542. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37543. quadNormal.normalize();
  37544. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37545. if (hasRings) {
  37546. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37547. }
  37548. else {
  37549. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37550. }
  37551. uvs.push(faceUV[s + 1].x, v);
  37552. uvs.push(faceUV[s + 1].z, v);
  37553. if (hasRings) {
  37554. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37555. }
  37556. else {
  37557. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37558. }
  37559. uvs.push(faceUV[s + 2].x, v);
  37560. uvs.push(faceUV[s + 2].z, v);
  37561. if (faceColors) {
  37562. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37563. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37564. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37565. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37566. }
  37567. }
  37568. if (cs !== s) {
  37569. cs = s;
  37570. }
  37571. }
  37572. }
  37573. // indices
  37574. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37575. var s;
  37576. i = 0;
  37577. for (s = 0; s < subdivisions; s++) {
  37578. var i0 = 0;
  37579. var i1 = 0;
  37580. var i2 = 0;
  37581. var i3 = 0;
  37582. for (j = 0; j < tessellation; j++) {
  37583. i0 = i * (e + 1) + j;
  37584. i1 = (i + 1) * (e + 1) + j;
  37585. i2 = i * (e + 1) + (j + 1);
  37586. i3 = (i + 1) * (e + 1) + (j + 1);
  37587. indices.push(i0, i1, i2);
  37588. indices.push(i3, i2, i1);
  37589. }
  37590. if (arc !== 1 && enclose) { // if enclose, add two quads
  37591. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37592. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37593. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37594. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37595. }
  37596. i = (hasRings) ? (i + 2) : (i + 1);
  37597. }
  37598. // Caps
  37599. var createCylinderCap = function (isTop) {
  37600. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37601. if (radius === 0) {
  37602. return;
  37603. }
  37604. // Cap positions, normals & uvs
  37605. var angle;
  37606. var circleVector;
  37607. var i;
  37608. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37609. var c = null;
  37610. if (faceColors) {
  37611. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37612. }
  37613. // cap center
  37614. var vbase = positions.length / 3;
  37615. var offset = isTop ? height / 2 : -height / 2;
  37616. var center = new BABYLON.Vector3(0, offset, 0);
  37617. positions.push(center.x, center.y, center.z);
  37618. normals.push(0, isTop ? 1 : -1, 0);
  37619. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37620. if (c) {
  37621. colors.push(c.r, c.g, c.b, c.a);
  37622. }
  37623. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37624. for (i = 0; i <= tessellation; i++) {
  37625. angle = Math.PI * 2 * i * arc / tessellation;
  37626. var cos = Math.cos(-angle);
  37627. var sin = Math.sin(-angle);
  37628. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37629. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37630. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37631. normals.push(0, isTop ? 1 : -1, 0);
  37632. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37633. if (c) {
  37634. colors.push(c.r, c.g, c.b, c.a);
  37635. }
  37636. }
  37637. // Cap indices
  37638. for (i = 0; i < tessellation; i++) {
  37639. if (!isTop) {
  37640. indices.push(vbase);
  37641. indices.push(vbase + (i + 1));
  37642. indices.push(vbase + (i + 2));
  37643. }
  37644. else {
  37645. indices.push(vbase);
  37646. indices.push(vbase + (i + 2));
  37647. indices.push(vbase + (i + 1));
  37648. }
  37649. }
  37650. };
  37651. // add caps to geometry
  37652. createCylinderCap(false);
  37653. createCylinderCap(true);
  37654. // Sides
  37655. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37656. var vertexData = new VertexData();
  37657. vertexData.indices = indices;
  37658. vertexData.positions = positions;
  37659. vertexData.normals = normals;
  37660. vertexData.uvs = uvs;
  37661. if (faceColors) {
  37662. vertexData.colors = colors;
  37663. }
  37664. return vertexData;
  37665. };
  37666. /**
  37667. * Creates the VertexData for a torus
  37668. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37669. * * diameter the diameter of the torus, optional default 1
  37670. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37671. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37672. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37673. * * 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)
  37674. * * 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)
  37675. * @returns the VertexData of the torus
  37676. */
  37677. VertexData.CreateTorus = function (options) {
  37678. var indices = [];
  37679. var positions = [];
  37680. var normals = [];
  37681. var uvs = [];
  37682. var diameter = options.diameter || 1;
  37683. var thickness = options.thickness || 0.5;
  37684. var tessellation = options.tessellation || 16;
  37685. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37686. var stride = tessellation + 1;
  37687. for (var i = 0; i <= tessellation; i++) {
  37688. var u = i / tessellation;
  37689. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37690. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37691. for (var j = 0; j <= tessellation; j++) {
  37692. var v = 1 - j / tessellation;
  37693. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37694. var dx = Math.cos(innerAngle);
  37695. var dy = Math.sin(innerAngle);
  37696. // Create a vertex.
  37697. var normal = new BABYLON.Vector3(dx, dy, 0);
  37698. var position = normal.scale(thickness / 2);
  37699. var textureCoordinate = new BABYLON.Vector2(u, v);
  37700. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37701. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37702. positions.push(position.x, position.y, position.z);
  37703. normals.push(normal.x, normal.y, normal.z);
  37704. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37705. // And create indices for two triangles.
  37706. var nextI = (i + 1) % stride;
  37707. var nextJ = (j + 1) % stride;
  37708. indices.push(i * stride + j);
  37709. indices.push(i * stride + nextJ);
  37710. indices.push(nextI * stride + j);
  37711. indices.push(i * stride + nextJ);
  37712. indices.push(nextI * stride + nextJ);
  37713. indices.push(nextI * stride + j);
  37714. }
  37715. }
  37716. // Sides
  37717. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37718. // Result
  37719. var vertexData = new VertexData();
  37720. vertexData.indices = indices;
  37721. vertexData.positions = positions;
  37722. vertexData.normals = normals;
  37723. vertexData.uvs = uvs;
  37724. return vertexData;
  37725. };
  37726. /**
  37727. * Creates the VertexData of the LineSystem
  37728. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37729. * - lines an array of lines, each line being an array of successive Vector3
  37730. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37731. * @returns the VertexData of the LineSystem
  37732. */
  37733. VertexData.CreateLineSystem = function (options) {
  37734. var indices = [];
  37735. var positions = [];
  37736. var lines = options.lines;
  37737. var colors = options.colors;
  37738. var vertexColors = [];
  37739. var idx = 0;
  37740. for (var l = 0; l < lines.length; l++) {
  37741. var points = lines[l];
  37742. for (var index = 0; index < points.length; index++) {
  37743. positions.push(points[index].x, points[index].y, points[index].z);
  37744. if (colors) {
  37745. var color = colors[l];
  37746. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37747. }
  37748. if (index > 0) {
  37749. indices.push(idx - 1);
  37750. indices.push(idx);
  37751. }
  37752. idx++;
  37753. }
  37754. }
  37755. var vertexData = new VertexData();
  37756. vertexData.indices = indices;
  37757. vertexData.positions = positions;
  37758. if (colors) {
  37759. vertexData.colors = vertexColors;
  37760. }
  37761. return vertexData;
  37762. };
  37763. /**
  37764. * Create the VertexData for a DashedLines
  37765. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37766. * - points an array successive Vector3
  37767. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37768. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37769. * - dashNb the intended total number of dashes, optional, default 200
  37770. * @returns the VertexData for the DashedLines
  37771. */
  37772. VertexData.CreateDashedLines = function (options) {
  37773. var dashSize = options.dashSize || 3;
  37774. var gapSize = options.gapSize || 1;
  37775. var dashNb = options.dashNb || 200;
  37776. var points = options.points;
  37777. var positions = new Array();
  37778. var indices = new Array();
  37779. var curvect = BABYLON.Vector3.Zero();
  37780. var lg = 0;
  37781. var nb = 0;
  37782. var shft = 0;
  37783. var dashshft = 0;
  37784. var curshft = 0;
  37785. var idx = 0;
  37786. var i = 0;
  37787. for (i = 0; i < points.length - 1; i++) {
  37788. points[i + 1].subtractToRef(points[i], curvect);
  37789. lg += curvect.length();
  37790. }
  37791. shft = lg / dashNb;
  37792. dashshft = dashSize * shft / (dashSize + gapSize);
  37793. for (i = 0; i < points.length - 1; i++) {
  37794. points[i + 1].subtractToRef(points[i], curvect);
  37795. nb = Math.floor(curvect.length() / shft);
  37796. curvect.normalize();
  37797. for (var j = 0; j < nb; j++) {
  37798. curshft = shft * j;
  37799. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37800. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37801. indices.push(idx, idx + 1);
  37802. idx += 2;
  37803. }
  37804. }
  37805. // Result
  37806. var vertexData = new VertexData();
  37807. vertexData.positions = positions;
  37808. vertexData.indices = indices;
  37809. return vertexData;
  37810. };
  37811. /**
  37812. * Creates the VertexData for a Ground
  37813. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37814. * - width the width (x direction) of the ground, optional, default 1
  37815. * - height the height (z direction) of the ground, optional, default 1
  37816. * - subdivisions the number of subdivisions per side, optional, default 1
  37817. * @returns the VertexData of the Ground
  37818. */
  37819. VertexData.CreateGround = function (options) {
  37820. var indices = [];
  37821. var positions = [];
  37822. var normals = [];
  37823. var uvs = [];
  37824. var row, col;
  37825. var width = options.width || 1;
  37826. var height = options.height || 1;
  37827. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37828. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37829. for (row = 0; row <= subdivisionsY; row++) {
  37830. for (col = 0; col <= subdivisionsX; col++) {
  37831. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37832. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37833. positions.push(position.x, position.y, position.z);
  37834. normals.push(normal.x, normal.y, normal.z);
  37835. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37836. }
  37837. }
  37838. for (row = 0; row < subdivisionsY; row++) {
  37839. for (col = 0; col < subdivisionsX; col++) {
  37840. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37841. indices.push(col + 1 + row * (subdivisionsX + 1));
  37842. indices.push(col + row * (subdivisionsX + 1));
  37843. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37844. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37845. indices.push(col + row * (subdivisionsX + 1));
  37846. }
  37847. }
  37848. // Result
  37849. var vertexData = new VertexData();
  37850. vertexData.indices = indices;
  37851. vertexData.positions = positions;
  37852. vertexData.normals = normals;
  37853. vertexData.uvs = uvs;
  37854. return vertexData;
  37855. };
  37856. /**
  37857. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37858. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37859. * * xmin the ground minimum X coordinate, optional, default -1
  37860. * * zmin the ground minimum Z coordinate, optional, default -1
  37861. * * xmax the ground maximum X coordinate, optional, default 1
  37862. * * zmax the ground maximum Z coordinate, optional, default 1
  37863. * * 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}
  37864. * * 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}
  37865. * @returns the VertexData of the TiledGround
  37866. */
  37867. VertexData.CreateTiledGround = function (options) {
  37868. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37869. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37870. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37871. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37872. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37873. var precision = options.precision || { w: 1, h: 1 };
  37874. var indices = new Array();
  37875. var positions = new Array();
  37876. var normals = new Array();
  37877. var uvs = new Array();
  37878. var row, col, tileRow, tileCol;
  37879. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37880. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37881. precision.w = (precision.w < 1) ? 1 : precision.w;
  37882. precision.h = (precision.h < 1) ? 1 : precision.h;
  37883. var tileSize = {
  37884. 'w': (xmax - xmin) / subdivisions.w,
  37885. 'h': (zmax - zmin) / subdivisions.h
  37886. };
  37887. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37888. // Indices
  37889. var base = positions.length / 3;
  37890. var rowLength = precision.w + 1;
  37891. for (row = 0; row < precision.h; row++) {
  37892. for (col = 0; col < precision.w; col++) {
  37893. var square = [
  37894. base + col + row * rowLength,
  37895. base + (col + 1) + row * rowLength,
  37896. base + (col + 1) + (row + 1) * rowLength,
  37897. base + col + (row + 1) * rowLength
  37898. ];
  37899. indices.push(square[1]);
  37900. indices.push(square[2]);
  37901. indices.push(square[3]);
  37902. indices.push(square[0]);
  37903. indices.push(square[1]);
  37904. indices.push(square[3]);
  37905. }
  37906. }
  37907. // Position, normals and uvs
  37908. var position = BABYLON.Vector3.Zero();
  37909. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37910. for (row = 0; row <= precision.h; row++) {
  37911. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37912. for (col = 0; col <= precision.w; col++) {
  37913. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37914. position.y = 0;
  37915. positions.push(position.x, position.y, position.z);
  37916. normals.push(normal.x, normal.y, normal.z);
  37917. uvs.push(col / precision.w, row / precision.h);
  37918. }
  37919. }
  37920. }
  37921. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37922. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37923. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37924. }
  37925. }
  37926. // Result
  37927. var vertexData = new VertexData();
  37928. vertexData.indices = indices;
  37929. vertexData.positions = positions;
  37930. vertexData.normals = normals;
  37931. vertexData.uvs = uvs;
  37932. return vertexData;
  37933. };
  37934. /**
  37935. * Creates the VertexData of the Ground designed from a heightmap
  37936. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37937. * * width the width (x direction) of the ground
  37938. * * height the height (z direction) of the ground
  37939. * * subdivisions the number of subdivisions per side
  37940. * * minHeight the minimum altitude on the ground, optional, default 0
  37941. * * maxHeight the maximum altitude on the ground, optional default 1
  37942. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37943. * * buffer the array holding the image color data
  37944. * * bufferWidth the width of image
  37945. * * bufferHeight the height of image
  37946. * @returns the VertexData of the Ground designed from a heightmap
  37947. */
  37948. VertexData.CreateGroundFromHeightMap = function (options) {
  37949. var indices = [];
  37950. var positions = [];
  37951. var normals = [];
  37952. var uvs = [];
  37953. var row, col;
  37954. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37955. // Vertices
  37956. for (row = 0; row <= options.subdivisions; row++) {
  37957. for (col = 0; col <= options.subdivisions; col++) {
  37958. 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));
  37959. // Compute height
  37960. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37961. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37962. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37963. var r = options.buffer[pos] / 255.0;
  37964. var g = options.buffer[pos + 1] / 255.0;
  37965. var b = options.buffer[pos + 2] / 255.0;
  37966. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37967. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37968. // Add vertex
  37969. positions.push(position.x, position.y, position.z);
  37970. normals.push(0, 0, 0);
  37971. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37972. }
  37973. }
  37974. // Indices
  37975. for (row = 0; row < options.subdivisions; row++) {
  37976. for (col = 0; col < options.subdivisions; col++) {
  37977. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37978. indices.push(col + 1 + row * (options.subdivisions + 1));
  37979. indices.push(col + row * (options.subdivisions + 1));
  37980. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37981. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37982. indices.push(col + row * (options.subdivisions + 1));
  37983. }
  37984. }
  37985. // Normals
  37986. VertexData.ComputeNormals(positions, indices, normals);
  37987. // Result
  37988. var vertexData = new VertexData();
  37989. vertexData.indices = indices;
  37990. vertexData.positions = positions;
  37991. vertexData.normals = normals;
  37992. vertexData.uvs = uvs;
  37993. return vertexData;
  37994. };
  37995. /**
  37996. * Creates the VertexData for a Plane
  37997. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37998. * * size sets the width and height of the plane to the value of size, optional default 1
  37999. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  38000. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  38001. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38002. * * 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)
  38003. * * 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)
  38004. * @returns the VertexData of the box
  38005. */
  38006. VertexData.CreatePlane = function (options) {
  38007. var indices = [];
  38008. var positions = [];
  38009. var normals = [];
  38010. var uvs = [];
  38011. var width = options.width || options.size || 1;
  38012. var height = options.height || options.size || 1;
  38013. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38014. // Vertices
  38015. var halfWidth = width / 2.0;
  38016. var halfHeight = height / 2.0;
  38017. positions.push(-halfWidth, -halfHeight, 0);
  38018. normals.push(0, 0, -1.0);
  38019. uvs.push(0.0, 0.0);
  38020. positions.push(halfWidth, -halfHeight, 0);
  38021. normals.push(0, 0, -1.0);
  38022. uvs.push(1.0, 0.0);
  38023. positions.push(halfWidth, halfHeight, 0);
  38024. normals.push(0, 0, -1.0);
  38025. uvs.push(1.0, 1.0);
  38026. positions.push(-halfWidth, halfHeight, 0);
  38027. normals.push(0, 0, -1.0);
  38028. uvs.push(0.0, 1.0);
  38029. // Indices
  38030. indices.push(0);
  38031. indices.push(1);
  38032. indices.push(2);
  38033. indices.push(0);
  38034. indices.push(2);
  38035. indices.push(3);
  38036. // Sides
  38037. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38038. // Result
  38039. var vertexData = new VertexData();
  38040. vertexData.indices = indices;
  38041. vertexData.positions = positions;
  38042. vertexData.normals = normals;
  38043. vertexData.uvs = uvs;
  38044. return vertexData;
  38045. };
  38046. /**
  38047. * Creates the VertexData of the Disc or regular Polygon
  38048. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  38049. * * radius the radius of the disc, optional default 0.5
  38050. * * tessellation the number of polygon sides, optional, default 64
  38051. * * 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
  38052. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38053. * * 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)
  38054. * * 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)
  38055. * @returns the VertexData of the box
  38056. */
  38057. VertexData.CreateDisc = function (options) {
  38058. var positions = new Array();
  38059. var indices = new Array();
  38060. var normals = new Array();
  38061. var uvs = new Array();
  38062. var radius = options.radius || 0.5;
  38063. var tessellation = options.tessellation || 64;
  38064. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38065. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38066. // positions and uvs
  38067. positions.push(0, 0, 0); // disc center first
  38068. uvs.push(0.5, 0.5);
  38069. var theta = Math.PI * 2 * arc;
  38070. var step = theta / tessellation;
  38071. for (var a = 0; a < theta; a += step) {
  38072. var x = Math.cos(a);
  38073. var y = Math.sin(a);
  38074. var u = (x + 1) / 2;
  38075. var v = (1 - y) / 2;
  38076. positions.push(radius * x, radius * y, 0);
  38077. uvs.push(u, v);
  38078. }
  38079. if (arc === 1) {
  38080. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38081. uvs.push(uvs[2], uvs[3]);
  38082. }
  38083. //indices
  38084. var vertexNb = positions.length / 3;
  38085. for (var i = 1; i < vertexNb - 1; i++) {
  38086. indices.push(i + 1, 0, i);
  38087. }
  38088. // result
  38089. VertexData.ComputeNormals(positions, indices, normals);
  38090. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38091. var vertexData = new VertexData();
  38092. vertexData.indices = indices;
  38093. vertexData.positions = positions;
  38094. vertexData.normals = normals;
  38095. vertexData.uvs = uvs;
  38096. return vertexData;
  38097. };
  38098. /**
  38099. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38100. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38101. * @param polygon a mesh built from polygonTriangulation.build()
  38102. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38103. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38104. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38105. * @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)
  38106. * @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)
  38107. * @returns the VertexData of the Polygon
  38108. */
  38109. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38110. var faceUV = fUV || new Array(3);
  38111. var faceColors = fColors;
  38112. var colors = [];
  38113. // default face colors and UV if undefined
  38114. for (var f = 0; f < 3; f++) {
  38115. if (faceUV[f] === undefined) {
  38116. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38117. }
  38118. if (faceColors && faceColors[f] === undefined) {
  38119. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38120. }
  38121. }
  38122. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38123. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38124. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38125. var indices = polygon.getIndices();
  38126. // set face colours and textures
  38127. var idx = 0;
  38128. var face = 0;
  38129. for (var index = 0; index < normals.length; index += 3) {
  38130. //Edge Face no. 1
  38131. if (Math.abs(normals[index + 1]) < 0.001) {
  38132. face = 1;
  38133. }
  38134. //Top Face no. 0
  38135. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38136. face = 0;
  38137. }
  38138. //Bottom Face no. 2
  38139. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38140. face = 2;
  38141. }
  38142. idx = index / 3;
  38143. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38144. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38145. if (faceColors) {
  38146. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38147. }
  38148. }
  38149. // sides
  38150. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38151. // Result
  38152. var vertexData = new VertexData();
  38153. vertexData.indices = indices;
  38154. vertexData.positions = positions;
  38155. vertexData.normals = normals;
  38156. vertexData.uvs = uvs;
  38157. if (faceColors) {
  38158. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38159. vertexData.colors = totalColors;
  38160. }
  38161. return vertexData;
  38162. };
  38163. /**
  38164. * Creates the VertexData of the IcoSphere
  38165. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38166. * * radius the radius of the IcoSphere, optional default 1
  38167. * * radiusX allows stretching in the x direction, optional, default radius
  38168. * * radiusY allows stretching in the y direction, optional, default radius
  38169. * * radiusZ allows stretching in the z direction, optional, default radius
  38170. * * flat when true creates a flat shaded mesh, optional, default true
  38171. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38172. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38173. * * 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)
  38174. * * 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)
  38175. * @returns the VertexData of the IcoSphere
  38176. */
  38177. VertexData.CreateIcoSphere = function (options) {
  38178. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38179. var radius = options.radius || 1;
  38180. var flat = (options.flat === undefined) ? true : options.flat;
  38181. var subdivisions = options.subdivisions || 4;
  38182. var radiusX = options.radiusX || radius;
  38183. var radiusY = options.radiusY || radius;
  38184. var radiusZ = options.radiusZ || radius;
  38185. var t = (1 + Math.sqrt(5)) / 2;
  38186. // 12 vertex x,y,z
  38187. var ico_vertices = [
  38188. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38189. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38190. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38191. ];
  38192. // index of 3 vertex makes a face of icopshere
  38193. var ico_indices = [
  38194. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38195. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38196. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38197. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38198. ];
  38199. // vertex for uv have aliased position, not for UV
  38200. var vertices_unalias_id = [
  38201. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38202. // vertex alias
  38203. 0,
  38204. 2,
  38205. 3,
  38206. 3,
  38207. 3,
  38208. 4,
  38209. 7,
  38210. 8,
  38211. 9,
  38212. 9,
  38213. 10,
  38214. 11 // 23: B + 12
  38215. ];
  38216. // uv as integer step (not pixels !)
  38217. var ico_vertexuv = [
  38218. 5, 1, 3, 1, 6, 4, 0, 0,
  38219. 5, 3, 4, 2, 2, 2, 4, 0,
  38220. 2, 0, 1, 1, 6, 0, 6, 2,
  38221. // vertex alias (for same vertex on different faces)
  38222. 0, 4,
  38223. 3, 3,
  38224. 4, 4,
  38225. 3, 1,
  38226. 4, 2,
  38227. 4, 4,
  38228. 0, 2,
  38229. 1, 1,
  38230. 2, 2,
  38231. 3, 3,
  38232. 1, 3,
  38233. 2, 4 // 23: B + 12
  38234. ];
  38235. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38236. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38237. // First island of uv mapping
  38238. // v = 4h 3+ 2
  38239. // v = 3h 9+ 4
  38240. // v = 2h 9+ 5 B
  38241. // v = 1h 9 1 0
  38242. // v = 0h 3 8 7 A
  38243. // u = 0 1 2 3 4 5 6 *a
  38244. // Second island of uv mapping
  38245. // v = 4h 0+ B+ 4+
  38246. // v = 3h A+ 2+
  38247. // v = 2h 7+ 6 3+
  38248. // v = 1h 8+ 3+
  38249. // v = 0h
  38250. // u = 0 1 2 3 4 5 6 *a
  38251. // Face layout on texture UV mapping
  38252. // ============
  38253. // \ 4 /\ 16 / ======
  38254. // \ / \ / /\ 11 /
  38255. // \/ 7 \/ / \ /
  38256. // ======= / 10 \/
  38257. // /\ 17 /\ =======
  38258. // / \ / \ \ 15 /\
  38259. // / 8 \/ 12 \ \ / \
  38260. // ============ \/ 6 \
  38261. // \ 18 /\ ============
  38262. // \ / \ \ 5 /\ 0 /
  38263. // \/ 13 \ \ / \ /
  38264. // ======= \/ 1 \/
  38265. // =============
  38266. // /\ 19 /\ 2 /\
  38267. // / \ / \ / \
  38268. // / 14 \/ 9 \/ 3 \
  38269. // ===================
  38270. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38271. var ustep = 138 / 1024;
  38272. var vstep = 239 / 1024;
  38273. var uoffset = 60 / 1024;
  38274. var voffset = 26 / 1024;
  38275. // Second island should have margin, not to touch the first island
  38276. // avoid any borderline artefact in pixel rounding
  38277. var island_u_offset = -40 / 1024;
  38278. var island_v_offset = +20 / 1024;
  38279. // face is either island 0 or 1 :
  38280. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38281. var island = [
  38282. 0, 0, 0, 0, 1,
  38283. 0, 0, 1, 1, 0,
  38284. 0, 0, 1, 1, 0,
  38285. 0, 1, 1, 1, 0 // 15 - 19
  38286. ];
  38287. var indices = new Array();
  38288. var positions = new Array();
  38289. var normals = new Array();
  38290. var uvs = new Array();
  38291. var current_indice = 0;
  38292. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38293. var face_vertex_pos = new Array(3);
  38294. var face_vertex_uv = new Array(3);
  38295. var v012;
  38296. for (v012 = 0; v012 < 3; v012++) {
  38297. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38298. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38299. }
  38300. // create all with normals
  38301. for (var face = 0; face < 20; face++) {
  38302. // 3 vertex per face
  38303. for (v012 = 0; v012 < 3; v012++) {
  38304. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38305. var v_id = ico_indices[3 * face + v012];
  38306. // vertex have 3D position (x,y,z)
  38307. 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]);
  38308. // Normalize to get normal, then scale to radius
  38309. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38310. // uv Coordinates from vertex ID
  38311. 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);
  38312. }
  38313. // Subdivide the face (interpolate pos, norm, uv)
  38314. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38315. // - norm is linear interpolation of vertex corner normal
  38316. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38317. // - uv is linear interpolation
  38318. //
  38319. // Topology is as below for sub-divide by 2
  38320. // vertex shown as v0,v1,v2
  38321. // interp index is i1 to progress in range [v0,v1[
  38322. // interp index is i2 to progress in range [v0,v2[
  38323. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38324. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38325. //
  38326. //
  38327. // i2 v2
  38328. // ^ ^
  38329. // / / \
  38330. // / / \
  38331. // / / \
  38332. // / / (0,1) \
  38333. // / #---------\
  38334. // / / \ (0,0)'/ \
  38335. // / / \ / \
  38336. // / / \ / \
  38337. // / / (0,0) \ / (1,0) \
  38338. // / #---------#---------\
  38339. // v0 v1
  38340. //
  38341. // --------------------> i1
  38342. //
  38343. // interp of (i1,i2):
  38344. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38345. // along i1 : lerp(x0,x1, i1/(S-i2))
  38346. //
  38347. // centroid of triangle is needed to get help normal computation
  38348. // (c1,c2) are used for centroid location
  38349. var interp_vertex = function (i1, i2, c1, c2) {
  38350. // vertex is interpolated from
  38351. // - face_vertex_pos[0..2]
  38352. // - face_vertex_uv[0..2]
  38353. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38354. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38355. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38356. pos_interp.normalize();
  38357. var vertex_normal;
  38358. if (flat) {
  38359. // in flat mode, recalculate normal as face centroid normal
  38360. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38361. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38362. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38363. }
  38364. else {
  38365. // in smooth mode, recalculate normal from each single vertex position
  38366. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38367. }
  38368. // Vertex normal need correction due to X,Y,Z radius scaling
  38369. vertex_normal.x /= radiusX;
  38370. vertex_normal.y /= radiusY;
  38371. vertex_normal.z /= radiusZ;
  38372. vertex_normal.normalize();
  38373. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38374. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38375. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38376. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38377. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38378. uvs.push(uv_interp.x, uv_interp.y);
  38379. // push each vertex has member of a face
  38380. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38381. indices.push(current_indice);
  38382. current_indice++;
  38383. };
  38384. for (var i2 = 0; i2 < subdivisions; i2++) {
  38385. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38386. // face : (i1,i2) for /\ :
  38387. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38388. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38389. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38390. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38391. if (i1 + i2 + 1 < subdivisions) {
  38392. // face : (i1,i2)' for \/ :
  38393. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38394. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38395. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38396. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38397. }
  38398. }
  38399. }
  38400. }
  38401. // Sides
  38402. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38403. // Result
  38404. var vertexData = new VertexData();
  38405. vertexData.indices = indices;
  38406. vertexData.positions = positions;
  38407. vertexData.normals = normals;
  38408. vertexData.uvs = uvs;
  38409. return vertexData;
  38410. };
  38411. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38412. /**
  38413. * Creates the VertexData for a Polyhedron
  38414. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38415. * * type provided types are:
  38416. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38417. * * 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)
  38418. * * size the size of the IcoSphere, optional default 1
  38419. * * sizeX allows stretching in the x direction, optional, default size
  38420. * * sizeY allows stretching in the y direction, optional, default size
  38421. * * sizeZ allows stretching in the z direction, optional, default size
  38422. * * 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
  38423. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38424. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38425. * * flat when true creates a flat shaded mesh, optional, default true
  38426. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38427. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38428. * * 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)
  38429. * * 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)
  38430. * @returns the VertexData of the Polyhedron
  38431. */
  38432. VertexData.CreatePolyhedron = function (options) {
  38433. // provided polyhedron types :
  38434. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38435. // 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)
  38436. var polyhedra = [];
  38437. 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]] };
  38438. 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]] };
  38439. polyhedra[2] = {
  38440. 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]],
  38441. 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]]
  38442. };
  38443. polyhedra[3] = {
  38444. 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]],
  38445. 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]]
  38446. };
  38447. polyhedra[4] = {
  38448. 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]],
  38449. 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]]
  38450. };
  38451. 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]] };
  38452. 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]] };
  38453. 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]] };
  38454. 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]] };
  38455. 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]] };
  38456. 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]] };
  38457. 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]] };
  38458. 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]] };
  38459. 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]] };
  38460. polyhedra[14] = {
  38461. 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]],
  38462. 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]]
  38463. };
  38464. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38465. var size = options.size;
  38466. var sizeX = options.sizeX || size || 1;
  38467. var sizeY = options.sizeY || size || 1;
  38468. var sizeZ = options.sizeZ || size || 1;
  38469. var data = options.custom || polyhedra[type];
  38470. var nbfaces = data.face.length;
  38471. var faceUV = options.faceUV || new Array(nbfaces);
  38472. var faceColors = options.faceColors;
  38473. var flat = (options.flat === undefined) ? true : options.flat;
  38474. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38475. var positions = new Array();
  38476. var indices = new Array();
  38477. var normals = new Array();
  38478. var uvs = new Array();
  38479. var colors = new Array();
  38480. var index = 0;
  38481. var faceIdx = 0; // face cursor in the array "indexes"
  38482. var indexes = new Array();
  38483. var i = 0;
  38484. var f = 0;
  38485. var u, v, ang, x, y, tmp;
  38486. // default face colors and UV if undefined
  38487. if (flat) {
  38488. for (f = 0; f < nbfaces; f++) {
  38489. if (faceColors && faceColors[f] === undefined) {
  38490. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38491. }
  38492. if (faceUV && faceUV[f] === undefined) {
  38493. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38494. }
  38495. }
  38496. }
  38497. if (!flat) {
  38498. for (i = 0; i < data.vertex.length; i++) {
  38499. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38500. uvs.push(0, 0);
  38501. }
  38502. for (f = 0; f < nbfaces; f++) {
  38503. for (i = 0; i < data.face[f].length - 2; i++) {
  38504. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38505. }
  38506. }
  38507. }
  38508. else {
  38509. for (f = 0; f < nbfaces; f++) {
  38510. var fl = data.face[f].length; // number of vertices of the current face
  38511. ang = 2 * Math.PI / fl;
  38512. x = 0.5 * Math.tan(ang / 2);
  38513. y = 0.5;
  38514. // positions, uvs, colors
  38515. for (i = 0; i < fl; i++) {
  38516. // positions
  38517. 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);
  38518. indexes.push(index);
  38519. index++;
  38520. // uvs
  38521. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38522. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38523. uvs.push(u, v);
  38524. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38525. y = x * Math.sin(ang) + y * Math.cos(ang);
  38526. x = tmp;
  38527. // colors
  38528. if (faceColors) {
  38529. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38530. }
  38531. }
  38532. // indices from indexes
  38533. for (i = 0; i < fl - 2; i++) {
  38534. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38535. }
  38536. faceIdx += fl;
  38537. }
  38538. }
  38539. VertexData.ComputeNormals(positions, indices, normals);
  38540. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38541. var vertexData = new VertexData();
  38542. vertexData.positions = positions;
  38543. vertexData.indices = indices;
  38544. vertexData.normals = normals;
  38545. vertexData.uvs = uvs;
  38546. if (faceColors && flat) {
  38547. vertexData.colors = colors;
  38548. }
  38549. return vertexData;
  38550. };
  38551. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38552. /**
  38553. * Creates the VertexData for a TorusKnot
  38554. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38555. * * radius the radius of the torus knot, optional, default 2
  38556. * * tube the thickness of the tube, optional, default 0.5
  38557. * * radialSegments the number of sides on each tube segments, optional, default 32
  38558. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38559. * * p the number of windings around the z axis, optional, default 2
  38560. * * q the number of windings around the x axis, optional, default 3
  38561. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38562. * * 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)
  38563. * * 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)
  38564. * @returns the VertexData of the Torus Knot
  38565. */
  38566. VertexData.CreateTorusKnot = function (options) {
  38567. var indices = new Array();
  38568. var positions = new Array();
  38569. var normals = new Array();
  38570. var uvs = new Array();
  38571. var radius = options.radius || 2;
  38572. var tube = options.tube || 0.5;
  38573. var radialSegments = options.radialSegments || 32;
  38574. var tubularSegments = options.tubularSegments || 32;
  38575. var p = options.p || 2;
  38576. var q = options.q || 3;
  38577. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38578. // Helper
  38579. var getPos = function (angle) {
  38580. var cu = Math.cos(angle);
  38581. var su = Math.sin(angle);
  38582. var quOverP = q / p * angle;
  38583. var cs = Math.cos(quOverP);
  38584. var tx = radius * (2 + cs) * 0.5 * cu;
  38585. var ty = radius * (2 + cs) * su * 0.5;
  38586. var tz = radius * Math.sin(quOverP) * 0.5;
  38587. return new BABYLON.Vector3(tx, ty, tz);
  38588. };
  38589. // Vertices
  38590. var i;
  38591. var j;
  38592. for (i = 0; i <= radialSegments; i++) {
  38593. var modI = i % radialSegments;
  38594. var u = modI / radialSegments * 2 * p * Math.PI;
  38595. var p1 = getPos(u);
  38596. var p2 = getPos(u + 0.01);
  38597. var tang = p2.subtract(p1);
  38598. var n = p2.add(p1);
  38599. var bitan = BABYLON.Vector3.Cross(tang, n);
  38600. n = BABYLON.Vector3.Cross(bitan, tang);
  38601. bitan.normalize();
  38602. n.normalize();
  38603. for (j = 0; j < tubularSegments; j++) {
  38604. var modJ = j % tubularSegments;
  38605. var v = modJ / tubularSegments * 2 * Math.PI;
  38606. var cx = -tube * Math.cos(v);
  38607. var cy = tube * Math.sin(v);
  38608. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38609. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38610. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38611. uvs.push(i / radialSegments);
  38612. uvs.push(j / tubularSegments);
  38613. }
  38614. }
  38615. for (i = 0; i < radialSegments; i++) {
  38616. for (j = 0; j < tubularSegments; j++) {
  38617. var jNext = (j + 1) % tubularSegments;
  38618. var a = i * tubularSegments + j;
  38619. var b = (i + 1) * tubularSegments + j;
  38620. var c = (i + 1) * tubularSegments + jNext;
  38621. var d = i * tubularSegments + jNext;
  38622. indices.push(d);
  38623. indices.push(b);
  38624. indices.push(a);
  38625. indices.push(d);
  38626. indices.push(c);
  38627. indices.push(b);
  38628. }
  38629. }
  38630. // Normals
  38631. VertexData.ComputeNormals(positions, indices, normals);
  38632. // Sides
  38633. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38634. // Result
  38635. var vertexData = new VertexData();
  38636. vertexData.indices = indices;
  38637. vertexData.positions = positions;
  38638. vertexData.normals = normals;
  38639. vertexData.uvs = uvs;
  38640. return vertexData;
  38641. };
  38642. // Tools
  38643. /**
  38644. * Compute normals for given positions and indices
  38645. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38646. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38647. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38648. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38649. * * facetNormals : optional array of facet normals (vector3)
  38650. * * facetPositions : optional array of facet positions (vector3)
  38651. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38652. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38653. * * bInfo : optional bounding info, required for facetPartitioning computation
  38654. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38655. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38656. * * useRightHandedSystem: optional boolean to for right handed system computation
  38657. * * depthSort : optional boolean to enable the facet depth sort computation
  38658. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38659. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38660. */
  38661. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38662. // temporary scalar variables
  38663. var index = 0; // facet index
  38664. var p1p2x = 0.0; // p1p2 vector x coordinate
  38665. var p1p2y = 0.0; // p1p2 vector y coordinate
  38666. var p1p2z = 0.0; // p1p2 vector z coordinate
  38667. var p3p2x = 0.0; // p3p2 vector x coordinate
  38668. var p3p2y = 0.0; // p3p2 vector y coordinate
  38669. var p3p2z = 0.0; // p3p2 vector z coordinate
  38670. var faceNormalx = 0.0; // facet normal x coordinate
  38671. var faceNormaly = 0.0; // facet normal y coordinate
  38672. var faceNormalz = 0.0; // facet normal z coordinate
  38673. var length = 0.0; // facet normal length before normalization
  38674. var v1x = 0; // vector1 x index in the positions array
  38675. var v1y = 0; // vector1 y index in the positions array
  38676. var v1z = 0; // vector1 z index in the positions array
  38677. var v2x = 0; // vector2 x index in the positions array
  38678. var v2y = 0; // vector2 y index in the positions array
  38679. var v2z = 0; // vector2 z index in the positions array
  38680. var v3x = 0; // vector3 x index in the positions array
  38681. var v3y = 0; // vector3 y index in the positions array
  38682. var v3z = 0; // vector3 z index in the positions array
  38683. var computeFacetNormals = false;
  38684. var computeFacetPositions = false;
  38685. var computeFacetPartitioning = false;
  38686. var computeDepthSort = false;
  38687. var faceNormalSign = 1;
  38688. var ratio = 0;
  38689. var distanceTo = null;
  38690. if (options) {
  38691. computeFacetNormals = (options.facetNormals) ? true : false;
  38692. computeFacetPositions = (options.facetPositions) ? true : false;
  38693. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38694. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38695. ratio = options.ratio || 0;
  38696. computeDepthSort = (options.depthSort) ? true : false;
  38697. distanceTo = (options.distanceTo);
  38698. if (computeDepthSort) {
  38699. if (distanceTo === undefined) {
  38700. distanceTo = BABYLON.Vector3.Zero();
  38701. }
  38702. var depthSortedFacets = options.depthSortedFacets;
  38703. }
  38704. }
  38705. // facetPartitioning reinit if needed
  38706. var xSubRatio = 0;
  38707. var ySubRatio = 0;
  38708. var zSubRatio = 0;
  38709. var subSq = 0;
  38710. if (computeFacetPartitioning && options && options.bbSize) {
  38711. var ox = 0; // X partitioning index for facet position
  38712. var oy = 0; // Y partinioning index for facet position
  38713. var oz = 0; // Z partinioning index for facet position
  38714. var b1x = 0; // X partitioning index for facet v1 vertex
  38715. var b1y = 0; // Y partitioning index for facet v1 vertex
  38716. var b1z = 0; // z partitioning index for facet v1 vertex
  38717. var b2x = 0; // X partitioning index for facet v2 vertex
  38718. var b2y = 0; // Y partitioning index for facet v2 vertex
  38719. var b2z = 0; // Z partitioning index for facet v2 vertex
  38720. var b3x = 0; // X partitioning index for facet v3 vertex
  38721. var b3y = 0; // Y partitioning index for facet v3 vertex
  38722. var b3z = 0; // Z partitioning index for facet v3 vertex
  38723. var block_idx_o = 0; // facet barycenter block index
  38724. var block_idx_v1 = 0; // v1 vertex block index
  38725. var block_idx_v2 = 0; // v2 vertex block index
  38726. var block_idx_v3 = 0; // v3 vertex block index
  38727. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38728. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38729. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38730. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38731. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38732. subSq = options.subDiv.max * options.subDiv.max;
  38733. options.facetPartitioning.length = 0;
  38734. }
  38735. // reset the normals
  38736. for (index = 0; index < positions.length; index++) {
  38737. normals[index] = 0.0;
  38738. }
  38739. // Loop : 1 indice triplet = 1 facet
  38740. var nbFaces = (indices.length / 3) | 0;
  38741. for (index = 0; index < nbFaces; index++) {
  38742. // get the indexes of the coordinates of each vertex of the facet
  38743. v1x = indices[index * 3] * 3;
  38744. v1y = v1x + 1;
  38745. v1z = v1x + 2;
  38746. v2x = indices[index * 3 + 1] * 3;
  38747. v2y = v2x + 1;
  38748. v2z = v2x + 2;
  38749. v3x = indices[index * 3 + 2] * 3;
  38750. v3y = v3x + 1;
  38751. v3z = v3x + 2;
  38752. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38753. p1p2y = positions[v1y] - positions[v2y];
  38754. p1p2z = positions[v1z] - positions[v2z];
  38755. p3p2x = positions[v3x] - positions[v2x];
  38756. p3p2y = positions[v3y] - positions[v2y];
  38757. p3p2z = positions[v3z] - positions[v2z];
  38758. // compute the face normal with the cross product
  38759. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38760. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38761. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38762. // normalize this normal and store it in the array facetData
  38763. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38764. length = (length === 0) ? 1.0 : length;
  38765. faceNormalx /= length;
  38766. faceNormaly /= length;
  38767. faceNormalz /= length;
  38768. if (computeFacetNormals && options) {
  38769. options.facetNormals[index].x = faceNormalx;
  38770. options.facetNormals[index].y = faceNormaly;
  38771. options.facetNormals[index].z = faceNormalz;
  38772. }
  38773. if (computeFacetPositions && options) {
  38774. // compute and the facet barycenter coordinates in the array facetPositions
  38775. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38776. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38777. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38778. }
  38779. if (computeFacetPartitioning && options) {
  38780. // store the facet indexes in arrays in the main facetPartitioning array :
  38781. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38782. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38783. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38784. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38785. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38786. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38787. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38788. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38789. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38790. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38791. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38792. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38793. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38794. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38795. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38796. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38797. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38798. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38799. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38800. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38801. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38802. // push each facet index in each block containing the vertex
  38803. options.facetPartitioning[block_idx_v1].push(index);
  38804. if (block_idx_v2 != block_idx_v1) {
  38805. options.facetPartitioning[block_idx_v2].push(index);
  38806. }
  38807. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38808. options.facetPartitioning[block_idx_v3].push(index);
  38809. }
  38810. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38811. options.facetPartitioning[block_idx_o].push(index);
  38812. }
  38813. }
  38814. if (computeDepthSort && options && options.facetPositions) {
  38815. var dsf = depthSortedFacets[index];
  38816. dsf.ind = index * 3;
  38817. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38818. }
  38819. // compute the normals anyway
  38820. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38821. normals[v1y] += faceNormaly;
  38822. normals[v1z] += faceNormalz;
  38823. normals[v2x] += faceNormalx;
  38824. normals[v2y] += faceNormaly;
  38825. normals[v2z] += faceNormalz;
  38826. normals[v3x] += faceNormalx;
  38827. normals[v3y] += faceNormaly;
  38828. normals[v3z] += faceNormalz;
  38829. }
  38830. // last normalization of each normal
  38831. for (index = 0; index < normals.length / 3; index++) {
  38832. faceNormalx = normals[index * 3];
  38833. faceNormaly = normals[index * 3 + 1];
  38834. faceNormalz = normals[index * 3 + 2];
  38835. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38836. length = (length === 0) ? 1.0 : length;
  38837. faceNormalx /= length;
  38838. faceNormaly /= length;
  38839. faceNormalz /= length;
  38840. normals[index * 3] = faceNormalx;
  38841. normals[index * 3 + 1] = faceNormaly;
  38842. normals[index * 3 + 2] = faceNormalz;
  38843. }
  38844. };
  38845. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38846. var li = indices.length;
  38847. var ln = normals.length;
  38848. var i;
  38849. var n;
  38850. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38851. switch (sideOrientation) {
  38852. case BABYLON.Mesh.FRONTSIDE:
  38853. // nothing changed
  38854. break;
  38855. case BABYLON.Mesh.BACKSIDE:
  38856. var tmp;
  38857. // indices
  38858. for (i = 0; i < li; i += 3) {
  38859. tmp = indices[i];
  38860. indices[i] = indices[i + 2];
  38861. indices[i + 2] = tmp;
  38862. }
  38863. // normals
  38864. for (n = 0; n < ln; n++) {
  38865. normals[n] = -normals[n];
  38866. }
  38867. break;
  38868. case BABYLON.Mesh.DOUBLESIDE:
  38869. // positions
  38870. var lp = positions.length;
  38871. var l = lp / 3;
  38872. for (var p = 0; p < lp; p++) {
  38873. positions[lp + p] = positions[p];
  38874. }
  38875. // indices
  38876. for (i = 0; i < li; i += 3) {
  38877. indices[i + li] = indices[i + 2] + l;
  38878. indices[i + 1 + li] = indices[i + 1] + l;
  38879. indices[i + 2 + li] = indices[i] + l;
  38880. }
  38881. // normals
  38882. for (n = 0; n < ln; n++) {
  38883. normals[ln + n] = -normals[n];
  38884. }
  38885. // uvs
  38886. var lu = uvs.length;
  38887. var u = 0;
  38888. for (u = 0; u < lu; u++) {
  38889. uvs[u + lu] = uvs[u];
  38890. }
  38891. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38892. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38893. u = 0;
  38894. for (i = 0; i < lu / 2; i++) {
  38895. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38896. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38897. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38898. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38899. u += 2;
  38900. }
  38901. break;
  38902. }
  38903. };
  38904. /**
  38905. * Applies VertexData created from the imported parameters to the geometry
  38906. * @param parsedVertexData the parsed data from an imported file
  38907. * @param geometry the geometry to apply the VertexData to
  38908. */
  38909. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38910. var vertexData = new VertexData();
  38911. // positions
  38912. var positions = parsedVertexData.positions;
  38913. if (positions) {
  38914. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38915. }
  38916. // normals
  38917. var normals = parsedVertexData.normals;
  38918. if (normals) {
  38919. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38920. }
  38921. // tangents
  38922. var tangents = parsedVertexData.tangents;
  38923. if (tangents) {
  38924. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38925. }
  38926. // uvs
  38927. var uvs = parsedVertexData.uvs;
  38928. if (uvs) {
  38929. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38930. }
  38931. // uv2s
  38932. var uv2s = parsedVertexData.uv2s;
  38933. if (uv2s) {
  38934. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38935. }
  38936. // uv3s
  38937. var uv3s = parsedVertexData.uv3s;
  38938. if (uv3s) {
  38939. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38940. }
  38941. // uv4s
  38942. var uv4s = parsedVertexData.uv4s;
  38943. if (uv4s) {
  38944. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38945. }
  38946. // uv5s
  38947. var uv5s = parsedVertexData.uv5s;
  38948. if (uv5s) {
  38949. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38950. }
  38951. // uv6s
  38952. var uv6s = parsedVertexData.uv6s;
  38953. if (uv6s) {
  38954. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38955. }
  38956. // colors
  38957. var colors = parsedVertexData.colors;
  38958. if (colors) {
  38959. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38960. }
  38961. // matricesIndices
  38962. var matricesIndices = parsedVertexData.matricesIndices;
  38963. if (matricesIndices) {
  38964. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38965. }
  38966. // matricesWeights
  38967. var matricesWeights = parsedVertexData.matricesWeights;
  38968. if (matricesWeights) {
  38969. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38970. }
  38971. // indices
  38972. var indices = parsedVertexData.indices;
  38973. if (indices) {
  38974. vertexData.indices = indices;
  38975. }
  38976. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38977. };
  38978. return VertexData;
  38979. }());
  38980. BABYLON.VertexData = VertexData;
  38981. })(BABYLON || (BABYLON = {}));
  38982. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38983. var BABYLON;
  38984. (function (BABYLON) {
  38985. /**
  38986. * Class used to store geometry data (vertex buffers + index buffer)
  38987. */
  38988. var Geometry = /** @class */ (function () {
  38989. /**
  38990. * Creates a new geometry
  38991. * @param id defines the unique ID
  38992. * @param scene defines the hosting scene
  38993. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38994. * @param updatable defines if geometry must be updatable (false by default)
  38995. * @param mesh defines the mesh that will be associated with the geometry
  38996. */
  38997. function Geometry(id, scene, vertexData, updatable, mesh) {
  38998. if (updatable === void 0) { updatable = false; }
  38999. if (mesh === void 0) { mesh = null; }
  39000. /**
  39001. * Gets the delay loading state of the geometry (none by default which means not delayed)
  39002. */
  39003. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39004. this._totalVertices = 0;
  39005. this._isDisposed = false;
  39006. this._indexBufferIsUpdatable = false;
  39007. this.id = id;
  39008. this._engine = scene.getEngine();
  39009. this._meshes = [];
  39010. this._scene = scene;
  39011. //Init vertex buffer cache
  39012. this._vertexBuffers = {};
  39013. this._indices = [];
  39014. this._updatable = updatable;
  39015. // vertexData
  39016. if (vertexData) {
  39017. this.setAllVerticesData(vertexData, updatable);
  39018. }
  39019. else {
  39020. this._totalVertices = 0;
  39021. this._indices = [];
  39022. }
  39023. if (this._engine.getCaps().vertexArrayObject) {
  39024. this._vertexArrayObjects = {};
  39025. }
  39026. // applyToMesh
  39027. if (mesh) {
  39028. if (mesh.getClassName() === "LinesMesh") {
  39029. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  39030. this._updateExtend();
  39031. }
  39032. this.applyToMesh(mesh);
  39033. mesh.computeWorldMatrix(true);
  39034. }
  39035. }
  39036. Object.defineProperty(Geometry.prototype, "boundingBias", {
  39037. /**
  39038. * 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
  39039. */
  39040. get: function () {
  39041. return this._boundingBias;
  39042. },
  39043. /**
  39044. * 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
  39045. */
  39046. set: function (value) {
  39047. if (this._boundingBias && this._boundingBias.equals(value)) {
  39048. return;
  39049. }
  39050. this._boundingBias = value.clone();
  39051. this._updateBoundingInfo(true, null);
  39052. },
  39053. enumerable: true,
  39054. configurable: true
  39055. });
  39056. /**
  39057. * Static function used to attach a new empty geometry to a mesh
  39058. * @param mesh defines the mesh to attach the geometry to
  39059. * @returns the new {BABYLON.Geometry}
  39060. */
  39061. Geometry.CreateGeometryForMesh = function (mesh) {
  39062. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  39063. geometry.applyToMesh(mesh);
  39064. return geometry;
  39065. };
  39066. Object.defineProperty(Geometry.prototype, "extend", {
  39067. /**
  39068. * Gets the current extend of the geometry
  39069. */
  39070. get: function () {
  39071. return this._extend;
  39072. },
  39073. enumerable: true,
  39074. configurable: true
  39075. });
  39076. /**
  39077. * Gets the hosting scene
  39078. * @returns the hosting {BABYLON.Scene}
  39079. */
  39080. Geometry.prototype.getScene = function () {
  39081. return this._scene;
  39082. };
  39083. /**
  39084. * Gets the hosting engine
  39085. * @returns the hosting {BABYLON.Engine}
  39086. */
  39087. Geometry.prototype.getEngine = function () {
  39088. return this._engine;
  39089. };
  39090. /**
  39091. * Defines if the geometry is ready to use
  39092. * @returns true if the geometry is ready to be used
  39093. */
  39094. Geometry.prototype.isReady = function () {
  39095. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39096. };
  39097. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39098. /**
  39099. * Gets a value indicating that the geometry should not be serialized
  39100. */
  39101. get: function () {
  39102. for (var index = 0; index < this._meshes.length; index++) {
  39103. if (!this._meshes[index].doNotSerialize) {
  39104. return false;
  39105. }
  39106. }
  39107. return true;
  39108. },
  39109. enumerable: true,
  39110. configurable: true
  39111. });
  39112. /** @hidden */
  39113. Geometry.prototype._rebuild = function () {
  39114. if (this._vertexArrayObjects) {
  39115. this._vertexArrayObjects = {};
  39116. }
  39117. // Index buffer
  39118. if (this._meshes.length !== 0 && this._indices) {
  39119. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39120. }
  39121. // Vertex buffers
  39122. for (var key in this._vertexBuffers) {
  39123. var vertexBuffer = this._vertexBuffers[key];
  39124. vertexBuffer._rebuild();
  39125. }
  39126. };
  39127. /**
  39128. * Affects all geometry data in one call
  39129. * @param vertexData defines the geometry data
  39130. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39131. */
  39132. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39133. vertexData.applyToGeometry(this, updatable);
  39134. this.notifyUpdate();
  39135. };
  39136. /**
  39137. * Set specific vertex data
  39138. * @param kind defines the data kind (Position, normal, etc...)
  39139. * @param data defines the vertex data to use
  39140. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39141. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39142. */
  39143. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39144. if (updatable === void 0) { updatable = false; }
  39145. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39146. this.setVerticesBuffer(buffer);
  39147. };
  39148. /**
  39149. * Removes a specific vertex data
  39150. * @param kind defines the data kind (Position, normal, etc...)
  39151. */
  39152. Geometry.prototype.removeVerticesData = function (kind) {
  39153. if (this._vertexBuffers[kind]) {
  39154. this._vertexBuffers[kind].dispose();
  39155. delete this._vertexBuffers[kind];
  39156. }
  39157. };
  39158. /**
  39159. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39160. * @param buffer defines the vertex buffer to use
  39161. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39162. */
  39163. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39164. if (totalVertices === void 0) { totalVertices = null; }
  39165. var kind = buffer.getKind();
  39166. if (this._vertexBuffers[kind]) {
  39167. this._vertexBuffers[kind].dispose();
  39168. }
  39169. this._vertexBuffers[kind] = buffer;
  39170. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39171. var data = buffer.getData();
  39172. if (totalVertices != null) {
  39173. this._totalVertices = totalVertices;
  39174. }
  39175. else {
  39176. if (data != null) {
  39177. this._totalVertices = data.length / (buffer.byteStride / 4);
  39178. }
  39179. }
  39180. this._updateExtend(data);
  39181. this._resetPointsArrayCache();
  39182. var meshes = this._meshes;
  39183. var numOfMeshes = meshes.length;
  39184. for (var index = 0; index < numOfMeshes; index++) {
  39185. var mesh = meshes[index];
  39186. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39187. mesh._createGlobalSubMesh(false);
  39188. mesh.computeWorldMatrix(true);
  39189. }
  39190. }
  39191. this.notifyUpdate(kind);
  39192. if (this._vertexArrayObjects) {
  39193. this._disposeVertexArrayObjects();
  39194. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39195. }
  39196. };
  39197. /**
  39198. * Update a specific vertex buffer
  39199. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39200. * It will do nothing if the buffer is not updatable
  39201. * @param kind defines the data kind (Position, normal, etc...)
  39202. * @param data defines the data to use
  39203. * @param offset defines the offset in the target buffer where to store the data
  39204. * @param useBytes set to true if the offset is in bytes
  39205. */
  39206. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39207. if (useBytes === void 0) { useBytes = false; }
  39208. var vertexBuffer = this.getVertexBuffer(kind);
  39209. if (!vertexBuffer) {
  39210. return;
  39211. }
  39212. vertexBuffer.updateDirectly(data, offset, useBytes);
  39213. this.notifyUpdate(kind);
  39214. };
  39215. /**
  39216. * Update a specific vertex buffer
  39217. * This function will create a new buffer if the current one is not updatable
  39218. * @param kind defines the data kind (Position, normal, etc...)
  39219. * @param data defines the data to use
  39220. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39221. */
  39222. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39223. if (updateExtends === void 0) { updateExtends = false; }
  39224. var vertexBuffer = this.getVertexBuffer(kind);
  39225. if (!vertexBuffer) {
  39226. return;
  39227. }
  39228. vertexBuffer.update(data);
  39229. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39230. this._updateBoundingInfo(updateExtends, data);
  39231. }
  39232. this.notifyUpdate(kind);
  39233. };
  39234. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39235. if (updateExtends) {
  39236. this._updateExtend(data);
  39237. }
  39238. var meshes = this._meshes;
  39239. var numOfMeshes = meshes.length;
  39240. this._resetPointsArrayCache();
  39241. for (var index = 0; index < numOfMeshes; index++) {
  39242. var mesh = meshes[index];
  39243. if (updateExtends) {
  39244. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39245. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39246. var subMesh = mesh.subMeshes[subIndex];
  39247. subMesh.refreshBoundingInfo();
  39248. }
  39249. }
  39250. }
  39251. };
  39252. /** @hidden */
  39253. Geometry.prototype._bind = function (effect, indexToBind) {
  39254. if (!effect) {
  39255. return;
  39256. }
  39257. if (indexToBind === undefined) {
  39258. indexToBind = this._indexBuffer;
  39259. }
  39260. var vbs = this.getVertexBuffers();
  39261. if (!vbs) {
  39262. return;
  39263. }
  39264. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39265. this._engine.bindBuffers(vbs, indexToBind, effect);
  39266. return;
  39267. }
  39268. // Using VAO
  39269. if (!this._vertexArrayObjects[effect.key]) {
  39270. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39271. }
  39272. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39273. };
  39274. /**
  39275. * Gets total number of vertices
  39276. * @returns the total number of vertices
  39277. */
  39278. Geometry.prototype.getTotalVertices = function () {
  39279. if (!this.isReady()) {
  39280. return 0;
  39281. }
  39282. return this._totalVertices;
  39283. };
  39284. /**
  39285. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39286. * @param kind defines the data kind (Position, normal, etc...)
  39287. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39288. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39289. * @returns a float array containing vertex data
  39290. */
  39291. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39292. var vertexBuffer = this.getVertexBuffer(kind);
  39293. if (!vertexBuffer) {
  39294. return null;
  39295. }
  39296. var data = vertexBuffer.getData();
  39297. if (!data) {
  39298. return null;
  39299. }
  39300. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39301. var count = this._totalVertices * vertexBuffer.getSize();
  39302. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39303. var copy_1 = new Array(count);
  39304. vertexBuffer.forEach(count, function (value, index) {
  39305. copy_1[index] = value;
  39306. });
  39307. return copy_1;
  39308. }
  39309. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39310. if (data instanceof Array) {
  39311. var offset = vertexBuffer.byteOffset / 4;
  39312. return BABYLON.Tools.Slice(data, offset, offset + count);
  39313. }
  39314. else if (data instanceof ArrayBuffer) {
  39315. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39316. }
  39317. else {
  39318. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39319. }
  39320. }
  39321. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39322. return BABYLON.Tools.Slice(data);
  39323. }
  39324. return data;
  39325. };
  39326. /**
  39327. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39328. * @param kind defines the data kind (Position, normal, etc...)
  39329. * @returns true if the vertex buffer with the specified kind is updatable
  39330. */
  39331. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39332. var vb = this._vertexBuffers[kind];
  39333. if (!vb) {
  39334. return false;
  39335. }
  39336. return vb.isUpdatable();
  39337. };
  39338. /**
  39339. * Gets a specific vertex buffer
  39340. * @param kind defines the data kind (Position, normal, etc...)
  39341. * @returns a {BABYLON.VertexBuffer}
  39342. */
  39343. Geometry.prototype.getVertexBuffer = function (kind) {
  39344. if (!this.isReady()) {
  39345. return null;
  39346. }
  39347. return this._vertexBuffers[kind];
  39348. };
  39349. /**
  39350. * Returns all vertex buffers
  39351. * @return an object holding all vertex buffers indexed by kind
  39352. */
  39353. Geometry.prototype.getVertexBuffers = function () {
  39354. if (!this.isReady()) {
  39355. return null;
  39356. }
  39357. return this._vertexBuffers;
  39358. };
  39359. /**
  39360. * Gets a boolean indicating if specific vertex buffer is present
  39361. * @param kind defines the data kind (Position, normal, etc...)
  39362. * @returns true if data is present
  39363. */
  39364. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39365. if (!this._vertexBuffers) {
  39366. if (this._delayInfo) {
  39367. return this._delayInfo.indexOf(kind) !== -1;
  39368. }
  39369. return false;
  39370. }
  39371. return this._vertexBuffers[kind] !== undefined;
  39372. };
  39373. /**
  39374. * Gets a list of all attached data kinds (Position, normal, etc...)
  39375. * @returns a list of string containing all kinds
  39376. */
  39377. Geometry.prototype.getVerticesDataKinds = function () {
  39378. var result = [];
  39379. var kind;
  39380. if (!this._vertexBuffers && this._delayInfo) {
  39381. for (kind in this._delayInfo) {
  39382. result.push(kind);
  39383. }
  39384. }
  39385. else {
  39386. for (kind in this._vertexBuffers) {
  39387. result.push(kind);
  39388. }
  39389. }
  39390. return result;
  39391. };
  39392. /**
  39393. * Update index buffer
  39394. * @param indices defines the indices to store in the index buffer
  39395. * @param offset defines the offset in the target buffer where to store the data
  39396. */
  39397. Geometry.prototype.updateIndices = function (indices, offset) {
  39398. if (!this._indexBuffer) {
  39399. return;
  39400. }
  39401. if (!this._indexBufferIsUpdatable) {
  39402. this.setIndices(indices, null, true);
  39403. }
  39404. else {
  39405. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39406. }
  39407. };
  39408. /**
  39409. * Creates a new index buffer
  39410. * @param indices defines the indices to store in the index buffer
  39411. * @param totalVertices defines the total number of vertices (could be null)
  39412. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39413. */
  39414. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39415. if (totalVertices === void 0) { totalVertices = null; }
  39416. if (updatable === void 0) { updatable = false; }
  39417. if (this._indexBuffer) {
  39418. this._engine._releaseBuffer(this._indexBuffer);
  39419. }
  39420. this._disposeVertexArrayObjects();
  39421. this._indices = indices;
  39422. this._indexBufferIsUpdatable = updatable;
  39423. if (this._meshes.length !== 0 && this._indices) {
  39424. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39425. }
  39426. if (totalVertices != undefined) { // including null and undefined
  39427. this._totalVertices = totalVertices;
  39428. }
  39429. var meshes = this._meshes;
  39430. var numOfMeshes = meshes.length;
  39431. for (var index = 0; index < numOfMeshes; index++) {
  39432. meshes[index]._createGlobalSubMesh(true);
  39433. }
  39434. this.notifyUpdate();
  39435. };
  39436. /**
  39437. * Return the total number of indices
  39438. * @returns the total number of indices
  39439. */
  39440. Geometry.prototype.getTotalIndices = function () {
  39441. if (!this.isReady()) {
  39442. return 0;
  39443. }
  39444. return this._indices.length;
  39445. };
  39446. /**
  39447. * Gets the index buffer array
  39448. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39449. * @returns the index buffer array
  39450. */
  39451. Geometry.prototype.getIndices = function (copyWhenShared) {
  39452. if (!this.isReady()) {
  39453. return null;
  39454. }
  39455. var orig = this._indices;
  39456. if (!copyWhenShared || this._meshes.length === 1) {
  39457. return orig;
  39458. }
  39459. else {
  39460. var len = orig.length;
  39461. var copy = [];
  39462. for (var i = 0; i < len; i++) {
  39463. copy.push(orig[i]);
  39464. }
  39465. return copy;
  39466. }
  39467. };
  39468. /**
  39469. * Gets the index buffer
  39470. * @return the index buffer
  39471. */
  39472. Geometry.prototype.getIndexBuffer = function () {
  39473. if (!this.isReady()) {
  39474. return null;
  39475. }
  39476. return this._indexBuffer;
  39477. };
  39478. /** @hidden */
  39479. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39480. if (effect === void 0) { effect = null; }
  39481. if (!effect || !this._vertexArrayObjects) {
  39482. return;
  39483. }
  39484. if (this._vertexArrayObjects[effect.key]) {
  39485. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39486. delete this._vertexArrayObjects[effect.key];
  39487. }
  39488. };
  39489. /**
  39490. * Release the associated resources for a specific mesh
  39491. * @param mesh defines the source mesh
  39492. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39493. */
  39494. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39495. var meshes = this._meshes;
  39496. var index = meshes.indexOf(mesh);
  39497. if (index === -1) {
  39498. return;
  39499. }
  39500. meshes.splice(index, 1);
  39501. mesh._geometry = null;
  39502. if (meshes.length === 0 && shouldDispose) {
  39503. this.dispose();
  39504. }
  39505. };
  39506. /**
  39507. * Apply current geometry to a given mesh
  39508. * @param mesh defines the mesh to apply geometry to
  39509. */
  39510. Geometry.prototype.applyToMesh = function (mesh) {
  39511. if (mesh._geometry === this) {
  39512. return;
  39513. }
  39514. var previousGeometry = mesh._geometry;
  39515. if (previousGeometry) {
  39516. previousGeometry.releaseForMesh(mesh);
  39517. }
  39518. var meshes = this._meshes;
  39519. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39520. mesh._geometry = this;
  39521. this._scene.pushGeometry(this);
  39522. meshes.push(mesh);
  39523. if (this.isReady()) {
  39524. this._applyToMesh(mesh);
  39525. }
  39526. else {
  39527. mesh._boundingInfo = this._boundingInfo;
  39528. }
  39529. };
  39530. Geometry.prototype._updateExtend = function (data) {
  39531. if (data === void 0) { data = null; }
  39532. if (!data) {
  39533. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39534. }
  39535. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39536. };
  39537. Geometry.prototype._applyToMesh = function (mesh) {
  39538. var numOfMeshes = this._meshes.length;
  39539. // vertexBuffers
  39540. for (var kind in this._vertexBuffers) {
  39541. if (numOfMeshes === 1) {
  39542. this._vertexBuffers[kind].create();
  39543. }
  39544. var buffer = this._vertexBuffers[kind].getBuffer();
  39545. if (buffer)
  39546. buffer.references = numOfMeshes;
  39547. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39548. if (!this._extend) {
  39549. this._updateExtend();
  39550. }
  39551. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39552. mesh._createGlobalSubMesh(false);
  39553. //bounding info was just created again, world matrix should be applied again.
  39554. mesh._updateBoundingInfo();
  39555. }
  39556. }
  39557. // indexBuffer
  39558. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39559. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39560. }
  39561. if (this._indexBuffer) {
  39562. this._indexBuffer.references = numOfMeshes;
  39563. }
  39564. };
  39565. Geometry.prototype.notifyUpdate = function (kind) {
  39566. if (this.onGeometryUpdated) {
  39567. this.onGeometryUpdated(this, kind);
  39568. }
  39569. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39570. var mesh = _a[_i];
  39571. mesh._markSubMeshesAsAttributesDirty();
  39572. }
  39573. };
  39574. /**
  39575. * Load the geometry if it was flagged as delay loaded
  39576. * @param scene defines the hosting scene
  39577. * @param onLoaded defines a callback called when the geometry is loaded
  39578. */
  39579. Geometry.prototype.load = function (scene, onLoaded) {
  39580. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39581. return;
  39582. }
  39583. if (this.isReady()) {
  39584. if (onLoaded) {
  39585. onLoaded();
  39586. }
  39587. return;
  39588. }
  39589. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39590. this._queueLoad(scene, onLoaded);
  39591. };
  39592. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39593. var _this = this;
  39594. if (!this.delayLoadingFile) {
  39595. return;
  39596. }
  39597. scene._addPendingData(this);
  39598. scene._loadFile(this.delayLoadingFile, function (data) {
  39599. if (!_this._delayLoadingFunction) {
  39600. return;
  39601. }
  39602. _this._delayLoadingFunction(JSON.parse(data), _this);
  39603. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39604. _this._delayInfo = [];
  39605. scene._removePendingData(_this);
  39606. var meshes = _this._meshes;
  39607. var numOfMeshes = meshes.length;
  39608. for (var index = 0; index < numOfMeshes; index++) {
  39609. _this._applyToMesh(meshes[index]);
  39610. }
  39611. if (onLoaded) {
  39612. onLoaded();
  39613. }
  39614. }, undefined, true);
  39615. };
  39616. /**
  39617. * Invert the geometry to move from a right handed system to a left handed one.
  39618. */
  39619. Geometry.prototype.toLeftHanded = function () {
  39620. // Flip faces
  39621. var tIndices = this.getIndices(false);
  39622. if (tIndices != null && tIndices.length > 0) {
  39623. for (var i = 0; i < tIndices.length; i += 3) {
  39624. var tTemp = tIndices[i + 0];
  39625. tIndices[i + 0] = tIndices[i + 2];
  39626. tIndices[i + 2] = tTemp;
  39627. }
  39628. this.setIndices(tIndices);
  39629. }
  39630. // Negate position.z
  39631. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39632. if (tPositions != null && tPositions.length > 0) {
  39633. for (var i = 0; i < tPositions.length; i += 3) {
  39634. tPositions[i + 2] = -tPositions[i + 2];
  39635. }
  39636. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39637. }
  39638. // Negate normal.z
  39639. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39640. if (tNormals != null && tNormals.length > 0) {
  39641. for (var i = 0; i < tNormals.length; i += 3) {
  39642. tNormals[i + 2] = -tNormals[i + 2];
  39643. }
  39644. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39645. }
  39646. };
  39647. // Cache
  39648. /** @hidden */
  39649. Geometry.prototype._resetPointsArrayCache = function () {
  39650. this._positions = null;
  39651. };
  39652. /** @hidden */
  39653. Geometry.prototype._generatePointsArray = function () {
  39654. if (this._positions)
  39655. return true;
  39656. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39657. if (!data || data.length === 0) {
  39658. return false;
  39659. }
  39660. this._positions = [];
  39661. for (var index = 0; index < data.length; index += 3) {
  39662. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39663. }
  39664. return true;
  39665. };
  39666. /**
  39667. * Gets a value indicating if the geometry is disposed
  39668. * @returns true if the geometry was disposed
  39669. */
  39670. Geometry.prototype.isDisposed = function () {
  39671. return this._isDisposed;
  39672. };
  39673. Geometry.prototype._disposeVertexArrayObjects = function () {
  39674. if (this._vertexArrayObjects) {
  39675. for (var kind in this._vertexArrayObjects) {
  39676. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39677. }
  39678. this._vertexArrayObjects = {};
  39679. }
  39680. };
  39681. /**
  39682. * Free all associated resources
  39683. */
  39684. Geometry.prototype.dispose = function () {
  39685. var meshes = this._meshes;
  39686. var numOfMeshes = meshes.length;
  39687. var index;
  39688. for (index = 0; index < numOfMeshes; index++) {
  39689. this.releaseForMesh(meshes[index]);
  39690. }
  39691. this._meshes = [];
  39692. this._disposeVertexArrayObjects();
  39693. for (var kind in this._vertexBuffers) {
  39694. this._vertexBuffers[kind].dispose();
  39695. }
  39696. this._vertexBuffers = {};
  39697. this._totalVertices = 0;
  39698. if (this._indexBuffer) {
  39699. this._engine._releaseBuffer(this._indexBuffer);
  39700. }
  39701. this._indexBuffer = null;
  39702. this._indices = [];
  39703. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39704. this.delayLoadingFile = null;
  39705. this._delayLoadingFunction = null;
  39706. this._delayInfo = [];
  39707. this._boundingInfo = null;
  39708. this._scene.removeGeometry(this);
  39709. this._isDisposed = true;
  39710. };
  39711. /**
  39712. * Clone the current geometry into a new geometry
  39713. * @param id defines the unique ID of the new geometry
  39714. * @returns a new geometry object
  39715. */
  39716. Geometry.prototype.copy = function (id) {
  39717. var vertexData = new BABYLON.VertexData();
  39718. vertexData.indices = [];
  39719. var indices = this.getIndices();
  39720. if (indices) {
  39721. for (var index = 0; index < indices.length; index++) {
  39722. vertexData.indices.push(indices[index]);
  39723. }
  39724. }
  39725. var updatable = false;
  39726. var stopChecking = false;
  39727. var kind;
  39728. for (kind in this._vertexBuffers) {
  39729. // using slice() to make a copy of the array and not just reference it
  39730. var data = this.getVerticesData(kind);
  39731. if (data instanceof Float32Array) {
  39732. vertexData.set(new Float32Array(data), kind);
  39733. }
  39734. else {
  39735. vertexData.set(data.slice(0), kind);
  39736. }
  39737. if (!stopChecking) {
  39738. var vb = this.getVertexBuffer(kind);
  39739. if (vb) {
  39740. updatable = vb.isUpdatable();
  39741. stopChecking = !updatable;
  39742. }
  39743. }
  39744. }
  39745. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39746. geometry.delayLoadState = this.delayLoadState;
  39747. geometry.delayLoadingFile = this.delayLoadingFile;
  39748. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39749. for (kind in this._delayInfo) {
  39750. geometry._delayInfo = geometry._delayInfo || [];
  39751. geometry._delayInfo.push(kind);
  39752. }
  39753. // Bounding info
  39754. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39755. return geometry;
  39756. };
  39757. /**
  39758. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39759. * @return a JSON representation of the current geometry data (without the vertices data)
  39760. */
  39761. Geometry.prototype.serialize = function () {
  39762. var serializationObject = {};
  39763. serializationObject.id = this.id;
  39764. serializationObject.updatable = this._updatable;
  39765. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39766. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39767. }
  39768. return serializationObject;
  39769. };
  39770. Geometry.prototype.toNumberArray = function (origin) {
  39771. if (Array.isArray(origin)) {
  39772. return origin;
  39773. }
  39774. else {
  39775. return Array.prototype.slice.call(origin);
  39776. }
  39777. };
  39778. /**
  39779. * Serialize all vertices data into a JSON oject
  39780. * @returns a JSON representation of the current geometry data
  39781. */
  39782. Geometry.prototype.serializeVerticeData = function () {
  39783. var serializationObject = this.serialize();
  39784. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39785. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39786. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39787. serializationObject.positions._updatable = true;
  39788. }
  39789. }
  39790. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39791. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39792. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39793. serializationObject.normals._updatable = true;
  39794. }
  39795. }
  39796. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39797. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39798. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39799. serializationObject.tangets._updatable = true;
  39800. }
  39801. }
  39802. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39803. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39804. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39805. serializationObject.uvs._updatable = true;
  39806. }
  39807. }
  39808. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39809. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39810. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39811. serializationObject.uv2s._updatable = true;
  39812. }
  39813. }
  39814. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39815. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39816. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39817. serializationObject.uv3s._updatable = true;
  39818. }
  39819. }
  39820. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39821. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39822. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39823. serializationObject.uv4s._updatable = true;
  39824. }
  39825. }
  39826. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39827. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39828. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39829. serializationObject.uv5s._updatable = true;
  39830. }
  39831. }
  39832. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39833. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39834. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39835. serializationObject.uv6s._updatable = true;
  39836. }
  39837. }
  39838. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39839. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39840. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39841. serializationObject.colors._updatable = true;
  39842. }
  39843. }
  39844. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39845. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39846. serializationObject.matricesIndices._isExpanded = true;
  39847. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39848. serializationObject.matricesIndices._updatable = true;
  39849. }
  39850. }
  39851. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39852. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39853. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39854. serializationObject.matricesWeights._updatable = true;
  39855. }
  39856. }
  39857. serializationObject.indices = this.toNumberArray(this.getIndices());
  39858. return serializationObject;
  39859. };
  39860. // Statics
  39861. /**
  39862. * Extracts a clone of a mesh geometry
  39863. * @param mesh defines the source mesh
  39864. * @param id defines the unique ID of the new geometry object
  39865. * @returns the new geometry object
  39866. */
  39867. Geometry.ExtractFromMesh = function (mesh, id) {
  39868. var geometry = mesh._geometry;
  39869. if (!geometry) {
  39870. return null;
  39871. }
  39872. return geometry.copy(id);
  39873. };
  39874. /**
  39875. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39876. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39877. * Be aware Math.random() could cause collisions, but:
  39878. * "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"
  39879. * @returns a string containing a new GUID
  39880. */
  39881. Geometry.RandomId = function () {
  39882. return BABYLON.Tools.RandomId();
  39883. };
  39884. /** @hidden */
  39885. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39886. var scene = mesh.getScene();
  39887. // Geometry
  39888. var geometryId = parsedGeometry.geometryId;
  39889. if (geometryId) {
  39890. var geometry = scene.getGeometryByID(geometryId);
  39891. if (geometry) {
  39892. geometry.applyToMesh(mesh);
  39893. }
  39894. }
  39895. else if (parsedGeometry instanceof ArrayBuffer) {
  39896. var binaryInfo = mesh._binaryInfo;
  39897. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39898. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39899. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39900. }
  39901. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39902. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39903. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39904. }
  39905. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39906. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39907. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39908. }
  39909. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39910. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39911. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39912. }
  39913. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39914. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39915. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39916. }
  39917. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39918. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39919. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39920. }
  39921. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39922. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39923. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39924. }
  39925. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39926. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39927. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39928. }
  39929. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39930. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39931. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39932. }
  39933. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39934. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39935. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39936. }
  39937. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39938. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39939. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39940. }
  39941. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39942. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39943. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39944. }
  39945. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39946. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39947. mesh.setIndices(indicesData, null);
  39948. }
  39949. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39950. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39951. mesh.subMeshes = [];
  39952. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39953. var materialIndex = subMeshesData[(i * 5) + 0];
  39954. var verticesStart = subMeshesData[(i * 5) + 1];
  39955. var verticesCount = subMeshesData[(i * 5) + 2];
  39956. var indexStart = subMeshesData[(i * 5) + 3];
  39957. var indexCount = subMeshesData[(i * 5) + 4];
  39958. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39959. }
  39960. }
  39961. }
  39962. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39963. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39964. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39965. if (parsedGeometry.tangents) {
  39966. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39967. }
  39968. if (parsedGeometry.uvs) {
  39969. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39970. }
  39971. if (parsedGeometry.uvs2) {
  39972. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39973. }
  39974. if (parsedGeometry.uvs3) {
  39975. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39976. }
  39977. if (parsedGeometry.uvs4) {
  39978. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39979. }
  39980. if (parsedGeometry.uvs5) {
  39981. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39982. }
  39983. if (parsedGeometry.uvs6) {
  39984. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39985. }
  39986. if (parsedGeometry.colors) {
  39987. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39988. }
  39989. if (parsedGeometry.matricesIndices) {
  39990. if (!parsedGeometry.matricesIndices._isExpanded) {
  39991. var floatIndices = [];
  39992. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39993. var matricesIndex = parsedGeometry.matricesIndices[i];
  39994. floatIndices.push(matricesIndex & 0x000000FF);
  39995. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39996. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39997. floatIndices.push(matricesIndex >> 24);
  39998. }
  39999. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  40000. }
  40001. else {
  40002. delete parsedGeometry.matricesIndices._isExpanded;
  40003. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  40004. }
  40005. }
  40006. if (parsedGeometry.matricesIndicesExtra) {
  40007. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  40008. var floatIndices = [];
  40009. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  40010. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  40011. floatIndices.push(matricesIndex & 0x000000FF);
  40012. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40013. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40014. floatIndices.push(matricesIndex >> 24);
  40015. }
  40016. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  40017. }
  40018. else {
  40019. delete parsedGeometry.matricesIndices._isExpanded;
  40020. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  40021. }
  40022. }
  40023. if (parsedGeometry.matricesWeights) {
  40024. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  40025. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  40026. }
  40027. if (parsedGeometry.matricesWeightsExtra) {
  40028. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  40029. }
  40030. mesh.setIndices(parsedGeometry.indices, null);
  40031. }
  40032. // SubMeshes
  40033. if (parsedGeometry.subMeshes) {
  40034. mesh.subMeshes = [];
  40035. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  40036. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  40037. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  40038. }
  40039. }
  40040. // Flat shading
  40041. if (mesh._shouldGenerateFlatShading) {
  40042. mesh.convertToFlatShadedMesh();
  40043. delete mesh._shouldGenerateFlatShading;
  40044. }
  40045. // Update
  40046. mesh.computeWorldMatrix(true);
  40047. // Octree
  40048. var sceneOctree = scene.selectionOctree;
  40049. if (sceneOctree !== undefined && sceneOctree !== null) {
  40050. sceneOctree.addMesh(mesh);
  40051. }
  40052. };
  40053. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  40054. var epsilon = 1e-3;
  40055. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40056. return;
  40057. }
  40058. var noInfluenceBoneIndex = 0.0;
  40059. if (parsedGeometry.skeletonId > -1) {
  40060. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40061. if (!skeleton) {
  40062. return;
  40063. }
  40064. noInfluenceBoneIndex = skeleton.bones.length;
  40065. }
  40066. else {
  40067. return;
  40068. }
  40069. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40070. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40071. var matricesWeights = parsedGeometry.matricesWeights;
  40072. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40073. var influencers = parsedGeometry.numBoneInfluencer;
  40074. var size = matricesWeights.length;
  40075. for (var i = 0; i < size; i += 4) {
  40076. var weight = 0.0;
  40077. var firstZeroWeight = -1;
  40078. for (var j = 0; j < 4; j++) {
  40079. var w = matricesWeights[i + j];
  40080. weight += w;
  40081. if (w < epsilon && firstZeroWeight < 0) {
  40082. firstZeroWeight = j;
  40083. }
  40084. }
  40085. if (matricesWeightsExtra) {
  40086. for (var j = 0; j < 4; j++) {
  40087. var w = matricesWeightsExtra[i + j];
  40088. weight += w;
  40089. if (w < epsilon && firstZeroWeight < 0) {
  40090. firstZeroWeight = j + 4;
  40091. }
  40092. }
  40093. }
  40094. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40095. firstZeroWeight = influencers - 1;
  40096. }
  40097. if (weight > epsilon) {
  40098. var mweight = 1.0 / weight;
  40099. for (var j = 0; j < 4; j++) {
  40100. matricesWeights[i + j] *= mweight;
  40101. }
  40102. if (matricesWeightsExtra) {
  40103. for (var j = 0; j < 4; j++) {
  40104. matricesWeightsExtra[i + j] *= mweight;
  40105. }
  40106. }
  40107. }
  40108. else {
  40109. if (firstZeroWeight >= 4) {
  40110. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40111. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40112. }
  40113. else {
  40114. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40115. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40116. }
  40117. }
  40118. }
  40119. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40120. if (parsedGeometry.matricesWeightsExtra) {
  40121. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40122. }
  40123. };
  40124. /**
  40125. * Create a new geometry from persisted data (Using .babylon file format)
  40126. * @param parsedVertexData defines the persisted data
  40127. * @param scene defines the hosting scene
  40128. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40129. * @returns the new geometry object
  40130. */
  40131. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40132. if (scene.getGeometryByID(parsedVertexData.id)) {
  40133. return null; // null since geometry could be something else than a box...
  40134. }
  40135. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40136. if (BABYLON.Tags) {
  40137. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40138. }
  40139. if (parsedVertexData.delayLoadingFile) {
  40140. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40141. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40142. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40143. geometry._delayInfo = [];
  40144. if (parsedVertexData.hasUVs) {
  40145. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40146. }
  40147. if (parsedVertexData.hasUVs2) {
  40148. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40149. }
  40150. if (parsedVertexData.hasUVs3) {
  40151. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40152. }
  40153. if (parsedVertexData.hasUVs4) {
  40154. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40155. }
  40156. if (parsedVertexData.hasUVs5) {
  40157. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40158. }
  40159. if (parsedVertexData.hasUVs6) {
  40160. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40161. }
  40162. if (parsedVertexData.hasColors) {
  40163. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40164. }
  40165. if (parsedVertexData.hasMatricesIndices) {
  40166. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40167. }
  40168. if (parsedVertexData.hasMatricesWeights) {
  40169. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40170. }
  40171. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40172. }
  40173. else {
  40174. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40175. }
  40176. scene.pushGeometry(geometry, true);
  40177. return geometry;
  40178. };
  40179. return Geometry;
  40180. }());
  40181. BABYLON.Geometry = Geometry;
  40182. // Primitives
  40183. /// Abstract class
  40184. /**
  40185. * Abstract class used to provide common services for all typed geometries
  40186. * @hidden
  40187. */
  40188. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40189. __extends(_PrimitiveGeometry, _super);
  40190. /**
  40191. * Creates a new typed geometry
  40192. * @param id defines the unique ID of the geometry
  40193. * @param scene defines the hosting scene
  40194. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40195. * @param mesh defines the hosting mesh (can be null)
  40196. */
  40197. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40198. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40199. if (mesh === void 0) { mesh = null; }
  40200. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40201. _this._canBeRegenerated = _canBeRegenerated;
  40202. _this._beingRegenerated = true;
  40203. _this.regenerate();
  40204. _this._beingRegenerated = false;
  40205. return _this;
  40206. }
  40207. /**
  40208. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40209. * @returns true if the geometry can be regenerated
  40210. */
  40211. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40212. return this._canBeRegenerated;
  40213. };
  40214. /**
  40215. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40216. */
  40217. _PrimitiveGeometry.prototype.regenerate = function () {
  40218. if (!this._canBeRegenerated) {
  40219. return;
  40220. }
  40221. this._beingRegenerated = true;
  40222. this.setAllVerticesData(this._regenerateVertexData(), false);
  40223. this._beingRegenerated = false;
  40224. };
  40225. /**
  40226. * Clone the geometry
  40227. * @param id defines the unique ID of the new geometry
  40228. * @returns the new geometry
  40229. */
  40230. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40231. return _super.prototype.copy.call(this, id);
  40232. };
  40233. // overrides
  40234. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40235. if (!this._beingRegenerated) {
  40236. return;
  40237. }
  40238. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40239. };
  40240. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40241. if (!this._beingRegenerated) {
  40242. return;
  40243. }
  40244. _super.prototype.setVerticesData.call(this, kind, data, false);
  40245. };
  40246. // to override
  40247. /** @hidden */
  40248. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40249. throw new Error("Abstract method");
  40250. };
  40251. _PrimitiveGeometry.prototype.copy = function (id) {
  40252. throw new Error("Must be overriden in sub-classes.");
  40253. };
  40254. _PrimitiveGeometry.prototype.serialize = function () {
  40255. var serializationObject = _super.prototype.serialize.call(this);
  40256. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40257. return serializationObject;
  40258. };
  40259. return _PrimitiveGeometry;
  40260. }(Geometry));
  40261. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40262. /**
  40263. * Creates a ribbon geometry
  40264. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40265. */
  40266. var RibbonGeometry = /** @class */ (function (_super) {
  40267. __extends(RibbonGeometry, _super);
  40268. /**
  40269. * Creates a ribbon geometry
  40270. * @param id defines the unique ID of the geometry
  40271. * @param scene defines the hosting scene
  40272. * @param pathArray defines the array of paths to use
  40273. * @param closeArray defines if the last path and the first path must be joined
  40274. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40275. * @param offset defines the offset between points
  40276. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40277. * @param mesh defines the hosting mesh (can be null)
  40278. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40279. */
  40280. function RibbonGeometry(id, scene,
  40281. /**
  40282. * Defines the array of paths to use
  40283. */
  40284. pathArray,
  40285. /**
  40286. * Defines if the last and first points of each path in your pathArray must be joined
  40287. */
  40288. closeArray,
  40289. /**
  40290. * Defines if the last and first points of each path in your pathArray must be joined
  40291. */
  40292. closePath,
  40293. /**
  40294. * Defines the offset between points
  40295. */
  40296. offset, canBeRegenerated, mesh,
  40297. /**
  40298. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40299. */
  40300. side) {
  40301. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40302. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40303. _this.pathArray = pathArray;
  40304. _this.closeArray = closeArray;
  40305. _this.closePath = closePath;
  40306. _this.offset = offset;
  40307. _this.side = side;
  40308. return _this;
  40309. }
  40310. /** @hidden */
  40311. RibbonGeometry.prototype._regenerateVertexData = function () {
  40312. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40313. };
  40314. RibbonGeometry.prototype.copy = function (id) {
  40315. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40316. };
  40317. return RibbonGeometry;
  40318. }(_PrimitiveGeometry));
  40319. BABYLON.RibbonGeometry = RibbonGeometry;
  40320. /**
  40321. * Creates a box geometry
  40322. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40323. */
  40324. var BoxGeometry = /** @class */ (function (_super) {
  40325. __extends(BoxGeometry, _super);
  40326. /**
  40327. * Creates a box geometry
  40328. * @param id defines the unique ID of the geometry
  40329. * @param scene defines the hosting scene
  40330. * @param size defines the zise of the box (width, height and depth are the same)
  40331. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40332. * @param mesh defines the hosting mesh (can be null)
  40333. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40334. */
  40335. function BoxGeometry(id, scene,
  40336. /**
  40337. * Defines the zise of the box (width, height and depth are the same)
  40338. */
  40339. size, canBeRegenerated, mesh,
  40340. /**
  40341. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40342. */
  40343. side) {
  40344. if (mesh === void 0) { mesh = null; }
  40345. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40346. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40347. _this.size = size;
  40348. _this.side = side;
  40349. return _this;
  40350. }
  40351. BoxGeometry.prototype._regenerateVertexData = function () {
  40352. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40353. };
  40354. BoxGeometry.prototype.copy = function (id) {
  40355. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40356. };
  40357. BoxGeometry.prototype.serialize = function () {
  40358. var serializationObject = _super.prototype.serialize.call(this);
  40359. serializationObject.size = this.size;
  40360. return serializationObject;
  40361. };
  40362. BoxGeometry.Parse = function (parsedBox, scene) {
  40363. if (scene.getGeometryByID(parsedBox.id)) {
  40364. return null; // null since geometry could be something else than a box...
  40365. }
  40366. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40367. if (BABYLON.Tags) {
  40368. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40369. }
  40370. scene.pushGeometry(box, true);
  40371. return box;
  40372. };
  40373. return BoxGeometry;
  40374. }(_PrimitiveGeometry));
  40375. BABYLON.BoxGeometry = BoxGeometry;
  40376. /**
  40377. * Creates a sphere geometry
  40378. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40379. */
  40380. var SphereGeometry = /** @class */ (function (_super) {
  40381. __extends(SphereGeometry, _super);
  40382. /**
  40383. * Create a new sphere geometry
  40384. * @param id defines the unique ID of the geometry
  40385. * @param scene defines the hosting scene
  40386. * @param segments defines the number of segments to use to create the sphere
  40387. * @param diameter defines the diameter of the sphere
  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 SphereGeometry(id, scene,
  40393. /**
  40394. * Defines the number of segments to use to create the sphere
  40395. */
  40396. segments,
  40397. /**
  40398. * Defines the diameter of the sphere
  40399. */
  40400. diameter, canBeRegenerated, mesh,
  40401. /**
  40402. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40403. */
  40404. side) {
  40405. if (mesh === void 0) { mesh = null; }
  40406. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40407. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40408. _this.segments = segments;
  40409. _this.diameter = diameter;
  40410. _this.side = side;
  40411. return _this;
  40412. }
  40413. SphereGeometry.prototype._regenerateVertexData = function () {
  40414. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40415. };
  40416. SphereGeometry.prototype.copy = function (id) {
  40417. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40418. };
  40419. SphereGeometry.prototype.serialize = function () {
  40420. var serializationObject = _super.prototype.serialize.call(this);
  40421. serializationObject.segments = this.segments;
  40422. serializationObject.diameter = this.diameter;
  40423. return serializationObject;
  40424. };
  40425. SphereGeometry.Parse = function (parsedSphere, scene) {
  40426. if (scene.getGeometryByID(parsedSphere.id)) {
  40427. return null; // null since geometry could be something else than a sphere...
  40428. }
  40429. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40430. if (BABYLON.Tags) {
  40431. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40432. }
  40433. scene.pushGeometry(sphere, true);
  40434. return sphere;
  40435. };
  40436. return SphereGeometry;
  40437. }(_PrimitiveGeometry));
  40438. BABYLON.SphereGeometry = SphereGeometry;
  40439. /**
  40440. * Creates a disc geometry
  40441. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40442. */
  40443. var DiscGeometry = /** @class */ (function (_super) {
  40444. __extends(DiscGeometry, _super);
  40445. /**
  40446. * Creates a new disc geometry
  40447. * @param id defines the unique ID of the geometry
  40448. * @param scene defines the hosting scene
  40449. * @param radius defines the radius of the disc
  40450. * @param tessellation defines the tesselation factor to apply to the disc
  40451. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40452. * @param mesh defines the hosting mesh (can be null)
  40453. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40454. */
  40455. function DiscGeometry(id, scene,
  40456. /**
  40457. * Defines the radius of the disc
  40458. */
  40459. radius,
  40460. /**
  40461. * Defines the tesselation factor to apply to the disc
  40462. */
  40463. tessellation, canBeRegenerated, mesh,
  40464. /**
  40465. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40466. */
  40467. side) {
  40468. if (mesh === void 0) { mesh = null; }
  40469. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40470. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40471. _this.radius = radius;
  40472. _this.tessellation = tessellation;
  40473. _this.side = side;
  40474. return _this;
  40475. }
  40476. DiscGeometry.prototype._regenerateVertexData = function () {
  40477. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40478. };
  40479. DiscGeometry.prototype.copy = function (id) {
  40480. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40481. };
  40482. return DiscGeometry;
  40483. }(_PrimitiveGeometry));
  40484. BABYLON.DiscGeometry = DiscGeometry;
  40485. /**
  40486. * Creates a new cylinder geometry
  40487. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40488. */
  40489. var CylinderGeometry = /** @class */ (function (_super) {
  40490. __extends(CylinderGeometry, _super);
  40491. /**
  40492. * Creates a new cylinder geometry
  40493. * @param id defines the unique ID of the geometry
  40494. * @param scene defines the hosting scene
  40495. * @param height defines the height of the cylinder
  40496. * @param diameterTop defines the diameter of the cylinder's top cap
  40497. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40498. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40499. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40500. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40501. * @param mesh defines the hosting mesh (can be null)
  40502. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40503. */
  40504. function CylinderGeometry(id, scene,
  40505. /**
  40506. * Defines the height of the cylinder
  40507. */
  40508. height,
  40509. /**
  40510. * Defines the diameter of the cylinder's top cap
  40511. */
  40512. diameterTop,
  40513. /**
  40514. * Defines the diameter of the cylinder's bottom cap
  40515. */
  40516. diameterBottom,
  40517. /**
  40518. * Defines the tessellation factor to apply to the cylinder
  40519. */
  40520. tessellation,
  40521. /**
  40522. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40523. */
  40524. subdivisions, canBeRegenerated, mesh,
  40525. /**
  40526. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40527. */
  40528. side) {
  40529. if (subdivisions === void 0) { subdivisions = 1; }
  40530. if (mesh === void 0) { mesh = null; }
  40531. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40532. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40533. _this.height = height;
  40534. _this.diameterTop = diameterTop;
  40535. _this.diameterBottom = diameterBottom;
  40536. _this.tessellation = tessellation;
  40537. _this.subdivisions = subdivisions;
  40538. _this.side = side;
  40539. return _this;
  40540. }
  40541. CylinderGeometry.prototype._regenerateVertexData = function () {
  40542. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40543. };
  40544. CylinderGeometry.prototype.copy = function (id) {
  40545. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40546. };
  40547. CylinderGeometry.prototype.serialize = function () {
  40548. var serializationObject = _super.prototype.serialize.call(this);
  40549. serializationObject.height = this.height;
  40550. serializationObject.diameterTop = this.diameterTop;
  40551. serializationObject.diameterBottom = this.diameterBottom;
  40552. serializationObject.tessellation = this.tessellation;
  40553. return serializationObject;
  40554. };
  40555. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40556. if (scene.getGeometryByID(parsedCylinder.id)) {
  40557. return null; // null since geometry could be something else than a cylinder...
  40558. }
  40559. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40560. if (BABYLON.Tags) {
  40561. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40562. }
  40563. scene.pushGeometry(cylinder, true);
  40564. return cylinder;
  40565. };
  40566. return CylinderGeometry;
  40567. }(_PrimitiveGeometry));
  40568. BABYLON.CylinderGeometry = CylinderGeometry;
  40569. /**
  40570. * Creates a new torus geometry
  40571. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40572. */
  40573. var TorusGeometry = /** @class */ (function (_super) {
  40574. __extends(TorusGeometry, _super);
  40575. /**
  40576. * Creates a new torus geometry
  40577. * @param id defines the unique ID of the geometry
  40578. * @param scene defines the hosting scene
  40579. * @param diameter defines the diameter of the torus
  40580. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40581. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40582. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40583. * @param mesh defines the hosting mesh (can be null)
  40584. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40585. */
  40586. function TorusGeometry(id, scene,
  40587. /**
  40588. * Defines the diameter of the torus
  40589. */
  40590. diameter,
  40591. /**
  40592. * Defines the thickness of the torus (ie. internal diameter)
  40593. */
  40594. thickness,
  40595. /**
  40596. * Defines the tesselation factor to apply to the torus
  40597. */
  40598. tessellation, canBeRegenerated, mesh,
  40599. /**
  40600. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40601. */
  40602. side) {
  40603. if (mesh === void 0) { mesh = null; }
  40604. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40605. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40606. _this.diameter = diameter;
  40607. _this.thickness = thickness;
  40608. _this.tessellation = tessellation;
  40609. _this.side = side;
  40610. return _this;
  40611. }
  40612. TorusGeometry.prototype._regenerateVertexData = function () {
  40613. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40614. };
  40615. TorusGeometry.prototype.copy = function (id) {
  40616. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40617. };
  40618. TorusGeometry.prototype.serialize = function () {
  40619. var serializationObject = _super.prototype.serialize.call(this);
  40620. serializationObject.diameter = this.diameter;
  40621. serializationObject.thickness = this.thickness;
  40622. serializationObject.tessellation = this.tessellation;
  40623. return serializationObject;
  40624. };
  40625. TorusGeometry.Parse = function (parsedTorus, scene) {
  40626. if (scene.getGeometryByID(parsedTorus.id)) {
  40627. return null; // null since geometry could be something else than a torus...
  40628. }
  40629. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40630. if (BABYLON.Tags) {
  40631. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40632. }
  40633. scene.pushGeometry(torus, true);
  40634. return torus;
  40635. };
  40636. return TorusGeometry;
  40637. }(_PrimitiveGeometry));
  40638. BABYLON.TorusGeometry = TorusGeometry;
  40639. /**
  40640. * Creates a new ground geometry
  40641. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40642. */
  40643. var GroundGeometry = /** @class */ (function (_super) {
  40644. __extends(GroundGeometry, _super);
  40645. /**
  40646. * Creates a new ground geometry
  40647. * @param id defines the unique ID of the geometry
  40648. * @param scene defines the hosting scene
  40649. * @param width defines the width of the ground
  40650. * @param height defines the height of the ground
  40651. * @param subdivisions defines the subdivisions to apply to the ground
  40652. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40653. * @param mesh defines the hosting mesh (can be null)
  40654. */
  40655. function GroundGeometry(id, scene,
  40656. /**
  40657. * Defines the width of the ground
  40658. */
  40659. width,
  40660. /**
  40661. * Defines the height of the ground
  40662. */
  40663. height,
  40664. /**
  40665. * Defines the subdivisions to apply to the ground
  40666. */
  40667. subdivisions, canBeRegenerated, mesh) {
  40668. if (mesh === void 0) { mesh = null; }
  40669. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40670. _this.width = width;
  40671. _this.height = height;
  40672. _this.subdivisions = subdivisions;
  40673. return _this;
  40674. }
  40675. GroundGeometry.prototype._regenerateVertexData = function () {
  40676. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40677. };
  40678. GroundGeometry.prototype.copy = function (id) {
  40679. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40680. };
  40681. GroundGeometry.prototype.serialize = function () {
  40682. var serializationObject = _super.prototype.serialize.call(this);
  40683. serializationObject.width = this.width;
  40684. serializationObject.height = this.height;
  40685. serializationObject.subdivisions = this.subdivisions;
  40686. return serializationObject;
  40687. };
  40688. GroundGeometry.Parse = function (parsedGround, scene) {
  40689. if (scene.getGeometryByID(parsedGround.id)) {
  40690. return null; // null since geometry could be something else than a ground...
  40691. }
  40692. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40693. if (BABYLON.Tags) {
  40694. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40695. }
  40696. scene.pushGeometry(ground, true);
  40697. return ground;
  40698. };
  40699. return GroundGeometry;
  40700. }(_PrimitiveGeometry));
  40701. BABYLON.GroundGeometry = GroundGeometry;
  40702. /**
  40703. * Creates a tiled ground geometry
  40704. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40705. */
  40706. var TiledGroundGeometry = /** @class */ (function (_super) {
  40707. __extends(TiledGroundGeometry, _super);
  40708. /**
  40709. * Creates a tiled ground geometry
  40710. * @param id defines the unique ID of the geometry
  40711. * @param scene defines the hosting scene
  40712. * @param xmin defines the minimum value on X axis
  40713. * @param zmin defines the minimum value on Z axis
  40714. * @param xmax defines the maximum value on X axis
  40715. * @param zmax defines the maximum value on Z axis
  40716. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40717. * @param precision defines the precision to use when computing the tiles
  40718. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40719. * @param mesh defines the hosting mesh (can be null)
  40720. */
  40721. function TiledGroundGeometry(id, scene,
  40722. /**
  40723. * Defines the minimum value on X axis
  40724. */
  40725. xmin,
  40726. /**
  40727. * Defines the minimum value on Z axis
  40728. */
  40729. zmin,
  40730. /**
  40731. * Defines the maximum value on X axis
  40732. */
  40733. xmax,
  40734. /**
  40735. * Defines the maximum value on Z axis
  40736. */
  40737. zmax,
  40738. /**
  40739. * Defines the subdivisions to apply to the ground
  40740. */
  40741. subdivisions,
  40742. /**
  40743. * Defines the precision to use when computing the tiles
  40744. */
  40745. precision, canBeRegenerated, mesh) {
  40746. if (mesh === void 0) { mesh = null; }
  40747. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40748. _this.xmin = xmin;
  40749. _this.zmin = zmin;
  40750. _this.xmax = xmax;
  40751. _this.zmax = zmax;
  40752. _this.subdivisions = subdivisions;
  40753. _this.precision = precision;
  40754. return _this;
  40755. }
  40756. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40757. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40758. };
  40759. TiledGroundGeometry.prototype.copy = function (id) {
  40760. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40761. };
  40762. return TiledGroundGeometry;
  40763. }(_PrimitiveGeometry));
  40764. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40765. /**
  40766. * Creates a plane geometry
  40767. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40768. */
  40769. var PlaneGeometry = /** @class */ (function (_super) {
  40770. __extends(PlaneGeometry, _super);
  40771. /**
  40772. * Creates a plane geometry
  40773. * @param id defines the unique ID of the geometry
  40774. * @param scene defines the hosting scene
  40775. * @param size defines the size of the plane (width === height)
  40776. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40777. * @param mesh defines the hosting mesh (can be null)
  40778. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40779. */
  40780. function PlaneGeometry(id, scene,
  40781. /**
  40782. * Defines the size of the plane (width === height)
  40783. */
  40784. size, canBeRegenerated, mesh,
  40785. /**
  40786. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40787. */
  40788. side) {
  40789. if (mesh === void 0) { mesh = null; }
  40790. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40791. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40792. _this.size = size;
  40793. _this.side = side;
  40794. return _this;
  40795. }
  40796. PlaneGeometry.prototype._regenerateVertexData = function () {
  40797. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40798. };
  40799. PlaneGeometry.prototype.copy = function (id) {
  40800. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40801. };
  40802. PlaneGeometry.prototype.serialize = function () {
  40803. var serializationObject = _super.prototype.serialize.call(this);
  40804. serializationObject.size = this.size;
  40805. return serializationObject;
  40806. };
  40807. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40808. if (scene.getGeometryByID(parsedPlane.id)) {
  40809. return null; // null since geometry could be something else than a ground...
  40810. }
  40811. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40812. if (BABYLON.Tags) {
  40813. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40814. }
  40815. scene.pushGeometry(plane, true);
  40816. return plane;
  40817. };
  40818. return PlaneGeometry;
  40819. }(_PrimitiveGeometry));
  40820. BABYLON.PlaneGeometry = PlaneGeometry;
  40821. /**
  40822. * Creates a torus knot geometry
  40823. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40824. */
  40825. var TorusKnotGeometry = /** @class */ (function (_super) {
  40826. __extends(TorusKnotGeometry, _super);
  40827. /**
  40828. * Creates a torus knot geometry
  40829. * @param id defines the unique ID of the geometry
  40830. * @param scene defines the hosting scene
  40831. * @param radius defines the radius of the torus knot
  40832. * @param tube defines the thickness of the torus knot tube
  40833. * @param radialSegments defines the number of radial segments
  40834. * @param tubularSegments defines the number of tubular segments
  40835. * @param p defines the first number of windings
  40836. * @param q defines the second number of windings
  40837. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40838. * @param mesh defines the hosting mesh (can be null)
  40839. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40840. */
  40841. function TorusKnotGeometry(id, scene,
  40842. /**
  40843. * Defines the radius of the torus knot
  40844. */
  40845. radius,
  40846. /**
  40847. * Defines the thickness of the torus knot tube
  40848. */
  40849. tube,
  40850. /**
  40851. * Defines the number of radial segments
  40852. */
  40853. radialSegments,
  40854. /**
  40855. * Defines the number of tubular segments
  40856. */
  40857. tubularSegments,
  40858. /**
  40859. * Defines the first number of windings
  40860. */
  40861. p,
  40862. /**
  40863. * Defines the second number of windings
  40864. */
  40865. q, canBeRegenerated, mesh,
  40866. /**
  40867. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40868. */
  40869. side) {
  40870. if (mesh === void 0) { mesh = null; }
  40871. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40872. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40873. _this.radius = radius;
  40874. _this.tube = tube;
  40875. _this.radialSegments = radialSegments;
  40876. _this.tubularSegments = tubularSegments;
  40877. _this.p = p;
  40878. _this.q = q;
  40879. _this.side = side;
  40880. return _this;
  40881. }
  40882. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40883. 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 });
  40884. };
  40885. TorusKnotGeometry.prototype.copy = function (id) {
  40886. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40887. };
  40888. TorusKnotGeometry.prototype.serialize = function () {
  40889. var serializationObject = _super.prototype.serialize.call(this);
  40890. serializationObject.radius = this.radius;
  40891. serializationObject.tube = this.tube;
  40892. serializationObject.radialSegments = this.radialSegments;
  40893. serializationObject.tubularSegments = this.tubularSegments;
  40894. serializationObject.p = this.p;
  40895. serializationObject.q = this.q;
  40896. return serializationObject;
  40897. };
  40898. ;
  40899. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40900. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40901. return null; // null since geometry could be something else than a ground...
  40902. }
  40903. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40904. if (BABYLON.Tags) {
  40905. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40906. }
  40907. scene.pushGeometry(torusKnot, true);
  40908. return torusKnot;
  40909. };
  40910. return TorusKnotGeometry;
  40911. }(_PrimitiveGeometry));
  40912. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40913. //}
  40914. })(BABYLON || (BABYLON = {}));
  40915. //# sourceMappingURL=babylon.geometry.js.map
  40916. var BABYLON;
  40917. (function (BABYLON) {
  40918. /**
  40919. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40920. */
  40921. var PerformanceMonitor = /** @class */ (function () {
  40922. /**
  40923. * constructor
  40924. * @param frameSampleSize The number of samples required to saturate the sliding window
  40925. */
  40926. function PerformanceMonitor(frameSampleSize) {
  40927. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40928. this._enabled = true;
  40929. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40930. }
  40931. /**
  40932. * Samples current frame
  40933. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40934. */
  40935. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40936. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40937. if (!this._enabled)
  40938. return;
  40939. if (this._lastFrameTimeMs != null) {
  40940. var dt = timeMs - this._lastFrameTimeMs;
  40941. this._rollingFrameTime.add(dt);
  40942. }
  40943. this._lastFrameTimeMs = timeMs;
  40944. };
  40945. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40946. /**
  40947. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40948. * @return Average frame time in milliseconds
  40949. */
  40950. get: function () {
  40951. return this._rollingFrameTime.average;
  40952. },
  40953. enumerable: true,
  40954. configurable: true
  40955. });
  40956. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40957. /**
  40958. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40959. * @return Frame time variance in milliseconds squared
  40960. */
  40961. get: function () {
  40962. return this._rollingFrameTime.variance;
  40963. },
  40964. enumerable: true,
  40965. configurable: true
  40966. });
  40967. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40968. /**
  40969. * Returns the frame time of the most recent frame
  40970. * @return Frame time in milliseconds
  40971. */
  40972. get: function () {
  40973. return this._rollingFrameTime.history(0);
  40974. },
  40975. enumerable: true,
  40976. configurable: true
  40977. });
  40978. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40979. /**
  40980. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40981. * @return Framerate in frames per second
  40982. */
  40983. get: function () {
  40984. return 1000.0 / this._rollingFrameTime.average;
  40985. },
  40986. enumerable: true,
  40987. configurable: true
  40988. });
  40989. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40990. /**
  40991. * Returns the average framerate in frames per second using the most recent frame time
  40992. * @return Framerate in frames per second
  40993. */
  40994. get: function () {
  40995. var history = this._rollingFrameTime.history(0);
  40996. if (history === 0) {
  40997. return 0;
  40998. }
  40999. return 1000.0 / history;
  41000. },
  41001. enumerable: true,
  41002. configurable: true
  41003. });
  41004. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41005. /**
  41006. * Returns true if enough samples have been taken to completely fill the sliding window
  41007. * @return true if saturated
  41008. */
  41009. get: function () {
  41010. return this._rollingFrameTime.isSaturated();
  41011. },
  41012. enumerable: true,
  41013. configurable: true
  41014. });
  41015. /**
  41016. * Enables contributions to the sliding window sample set
  41017. */
  41018. PerformanceMonitor.prototype.enable = function () {
  41019. this._enabled = true;
  41020. };
  41021. /**
  41022. * Disables contributions to the sliding window sample set
  41023. * Samples will not be interpolated over the disabled period
  41024. */
  41025. PerformanceMonitor.prototype.disable = function () {
  41026. this._enabled = false;
  41027. //clear last sample to avoid interpolating over the disabled period when next enabled
  41028. this._lastFrameTimeMs = null;
  41029. };
  41030. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41031. /**
  41032. * Returns true if sampling is enabled
  41033. * @return true if enabled
  41034. */
  41035. get: function () {
  41036. return this._enabled;
  41037. },
  41038. enumerable: true,
  41039. configurable: true
  41040. });
  41041. /**
  41042. * Resets performance monitor
  41043. */
  41044. PerformanceMonitor.prototype.reset = function () {
  41045. //clear last sample to avoid interpolating over the disabled period when next enabled
  41046. this._lastFrameTimeMs = null;
  41047. //wipe record
  41048. this._rollingFrameTime.reset();
  41049. };
  41050. return PerformanceMonitor;
  41051. }());
  41052. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41053. /**
  41054. * RollingAverage
  41055. *
  41056. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41057. */
  41058. var RollingAverage = /** @class */ (function () {
  41059. /**
  41060. * constructor
  41061. * @param length The number of samples required to saturate the sliding window
  41062. */
  41063. function RollingAverage(length) {
  41064. this._samples = new Array(length);
  41065. this.reset();
  41066. }
  41067. /**
  41068. * Adds a sample to the sample set
  41069. * @param v The sample value
  41070. */
  41071. RollingAverage.prototype.add = function (v) {
  41072. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41073. var delta;
  41074. //we need to check if we've already wrapped round
  41075. if (this.isSaturated()) {
  41076. //remove bottom of stack from mean
  41077. var bottomValue = this._samples[this._pos];
  41078. delta = bottomValue - this.average;
  41079. this.average -= delta / (this._sampleCount - 1);
  41080. this._m2 -= delta * (bottomValue - this.average);
  41081. }
  41082. else {
  41083. this._sampleCount++;
  41084. }
  41085. //add new value to mean
  41086. delta = v - this.average;
  41087. this.average += delta / (this._sampleCount);
  41088. this._m2 += delta * (v - this.average);
  41089. //set the new variance
  41090. this.variance = this._m2 / (this._sampleCount - 1);
  41091. this._samples[this._pos] = v;
  41092. this._pos++;
  41093. this._pos %= this._samples.length; //positive wrap around
  41094. };
  41095. /**
  41096. * Returns previously added values or null if outside of history or outside the sliding window domain
  41097. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41098. * @return Value previously recorded with add() or null if outside of range
  41099. */
  41100. RollingAverage.prototype.history = function (i) {
  41101. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41102. return 0;
  41103. }
  41104. var i0 = this._wrapPosition(this._pos - 1.0);
  41105. return this._samples[this._wrapPosition(i0 - i)];
  41106. };
  41107. /**
  41108. * Returns true if enough samples have been taken to completely fill the sliding window
  41109. * @return true if sample-set saturated
  41110. */
  41111. RollingAverage.prototype.isSaturated = function () {
  41112. return this._sampleCount >= this._samples.length;
  41113. };
  41114. /**
  41115. * Resets the rolling average (equivalent to 0 samples taken so far)
  41116. */
  41117. RollingAverage.prototype.reset = function () {
  41118. this.average = 0;
  41119. this.variance = 0;
  41120. this._sampleCount = 0;
  41121. this._pos = 0;
  41122. this._m2 = 0;
  41123. };
  41124. /**
  41125. * Wraps a value around the sample range boundaries
  41126. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41127. * @return Wrapped position in sample range
  41128. */
  41129. RollingAverage.prototype._wrapPosition = function (i) {
  41130. var max = this._samples.length;
  41131. return ((i % max) + max) % max;
  41132. };
  41133. return RollingAverage;
  41134. }());
  41135. BABYLON.RollingAverage = RollingAverage;
  41136. })(BABYLON || (BABYLON = {}));
  41137. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41138. var BABYLON;
  41139. (function (BABYLON) {
  41140. /**
  41141. * "Static Class" containing the most commonly used helper while dealing with material for
  41142. * rendering purpose.
  41143. *
  41144. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41145. *
  41146. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41147. */
  41148. var MaterialHelper = /** @class */ (function () {
  41149. function MaterialHelper() {
  41150. }
  41151. /**
  41152. * Bind the current view position to an effect.
  41153. * @param effect The effect to be bound
  41154. * @param scene The scene the eyes position is used from
  41155. */
  41156. MaterialHelper.BindEyePosition = function (effect, scene) {
  41157. if (scene._forcedViewPosition) {
  41158. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41159. return;
  41160. }
  41161. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41162. };
  41163. /**
  41164. * Helps preparing the defines values about the UVs in used in the effect.
  41165. * UVs are shared as much as we can accross chanels in the shaders.
  41166. * @param texture The texture we are preparing the UVs for
  41167. * @param defines The defines to update
  41168. * @param key The chanel key "diffuse", "specular"... used in the shader
  41169. */
  41170. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41171. defines._needUVs = true;
  41172. defines[key] = true;
  41173. if (texture.getTextureMatrix().isIdentity(true)) {
  41174. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41175. if (texture.coordinatesIndex === 0) {
  41176. defines["MAINUV1"] = true;
  41177. }
  41178. else {
  41179. defines["MAINUV2"] = true;
  41180. }
  41181. }
  41182. else {
  41183. defines[key + "DIRECTUV"] = 0;
  41184. }
  41185. };
  41186. /**
  41187. * Binds a texture matrix value to its corrsponding uniform
  41188. * @param texture The texture to bind the matrix for
  41189. * @param uniformBuffer The uniform buffer receivin the data
  41190. * @param key The chanel key "diffuse", "specular"... used in the shader
  41191. */
  41192. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41193. var matrix = texture.getTextureMatrix();
  41194. if (!matrix.isIdentity(true)) {
  41195. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41196. }
  41197. };
  41198. /**
  41199. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41200. * @param mesh defines the current mesh
  41201. * @param scene defines the current scene
  41202. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41203. * @param pointsCloud defines if point cloud rendering has to be turned on
  41204. * @param fogEnabled defines if fog has to be turned on
  41205. * @param alphaTest defines if alpha testing has to be turned on
  41206. * @param defines defines the current list of defines
  41207. */
  41208. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41209. if (defines._areMiscDirty) {
  41210. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41211. defines["POINTSIZE"] = pointsCloud;
  41212. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41213. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41214. defines["ALPHATEST"] = alphaTest;
  41215. }
  41216. };
  41217. /**
  41218. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41219. * @param scene defines the current scene
  41220. * @param engine defines the current engine
  41221. * @param defines specifies the list of active defines
  41222. * @param useInstances defines if instances have to be turned on
  41223. * @param useClipPlane defines if clip plane have to be turned on
  41224. */
  41225. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41226. if (useClipPlane === void 0) { useClipPlane = null; }
  41227. var changed = false;
  41228. if (useClipPlane == null) {
  41229. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41230. }
  41231. if (defines["CLIPPLANE"] !== useClipPlane) {
  41232. defines["CLIPPLANE"] = useClipPlane;
  41233. changed = true;
  41234. }
  41235. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41236. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41237. changed = true;
  41238. }
  41239. if (defines["INSTANCES"] !== useInstances) {
  41240. defines["INSTANCES"] = useInstances;
  41241. changed = true;
  41242. }
  41243. if (changed) {
  41244. defines.markAsUnprocessed();
  41245. }
  41246. };
  41247. /**
  41248. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41249. * @param mesh The mesh containing the geometry data we will draw
  41250. * @param defines The defines to update
  41251. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41252. * @param useBones Precise whether bones should be used or not (override mesh info)
  41253. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41254. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41255. * @returns false if defines are considered not dirty and have not been checked
  41256. */
  41257. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41258. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41259. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41260. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41261. return false;
  41262. }
  41263. defines._normals = defines._needNormals;
  41264. defines._uvs = defines._needUVs;
  41265. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41266. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41267. defines["TANGENT"] = true;
  41268. }
  41269. if (defines._needUVs) {
  41270. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41271. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41272. }
  41273. else {
  41274. defines["UV1"] = false;
  41275. defines["UV2"] = false;
  41276. }
  41277. if (useVertexColor) {
  41278. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41279. defines["VERTEXCOLOR"] = hasVertexColors;
  41280. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41281. }
  41282. if (useBones) {
  41283. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41284. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41285. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41286. }
  41287. else {
  41288. defines["NUM_BONE_INFLUENCERS"] = 0;
  41289. defines["BonesPerMesh"] = 0;
  41290. }
  41291. }
  41292. if (useMorphTargets) {
  41293. var manager = mesh.morphTargetManager;
  41294. if (manager) {
  41295. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41296. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41297. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41298. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41299. }
  41300. else {
  41301. defines["MORPHTARGETS_TANGENT"] = false;
  41302. defines["MORPHTARGETS_NORMAL"] = false;
  41303. defines["MORPHTARGETS"] = false;
  41304. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41305. }
  41306. }
  41307. return true;
  41308. };
  41309. /**
  41310. * Prepares the defines related to the light information passed in parameter
  41311. * @param scene The scene we are intending to draw
  41312. * @param mesh The mesh the effect is compiling for
  41313. * @param defines The defines to update
  41314. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41315. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41316. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41317. * @returns true if normals will be required for the rest of the effect
  41318. */
  41319. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41320. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41321. if (disableLighting === void 0) { disableLighting = false; }
  41322. if (!defines._areLightsDirty) {
  41323. return defines._needNormals;
  41324. }
  41325. var lightIndex = 0;
  41326. var needNormals = false;
  41327. var needRebuild = false;
  41328. var lightmapMode = false;
  41329. var shadowEnabled = false;
  41330. var specularEnabled = false;
  41331. if (scene.lightsEnabled && !disableLighting) {
  41332. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41333. var light = _a[_i];
  41334. needNormals = true;
  41335. if (defines["LIGHT" + lightIndex] === undefined) {
  41336. needRebuild = true;
  41337. }
  41338. defines["LIGHT" + lightIndex] = true;
  41339. defines["SPOTLIGHT" + lightIndex] = false;
  41340. defines["HEMILIGHT" + lightIndex] = false;
  41341. defines["POINTLIGHT" + lightIndex] = false;
  41342. defines["DIRLIGHT" + lightIndex] = false;
  41343. var type;
  41344. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41345. type = "SPOTLIGHT" + lightIndex;
  41346. var spotLight = light;
  41347. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  41348. }
  41349. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41350. type = "HEMILIGHT" + lightIndex;
  41351. }
  41352. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41353. type = "POINTLIGHT" + lightIndex;
  41354. }
  41355. else {
  41356. type = "DIRLIGHT" + lightIndex;
  41357. }
  41358. defines[type] = true;
  41359. // Specular
  41360. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41361. specularEnabled = true;
  41362. }
  41363. // Shadows
  41364. defines["SHADOW" + lightIndex] = false;
  41365. defines["SHADOWPCF" + lightIndex] = false;
  41366. defines["SHADOWPCSS" + lightIndex] = false;
  41367. defines["SHADOWPOISSON" + lightIndex] = false;
  41368. defines["SHADOWESM" + lightIndex] = false;
  41369. defines["SHADOWCUBE" + lightIndex] = false;
  41370. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41371. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41372. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41373. var shadowGenerator = light.getShadowGenerator();
  41374. if (shadowGenerator) {
  41375. shadowEnabled = true;
  41376. shadowGenerator.prepareDefines(defines, lightIndex);
  41377. }
  41378. }
  41379. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41380. lightmapMode = true;
  41381. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41382. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41383. }
  41384. else {
  41385. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41386. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41387. }
  41388. lightIndex++;
  41389. if (lightIndex === maxSimultaneousLights)
  41390. break;
  41391. }
  41392. }
  41393. defines["SPECULARTERM"] = specularEnabled;
  41394. defines["SHADOWS"] = shadowEnabled;
  41395. // Resetting all other lights if any
  41396. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41397. if (defines["LIGHT" + index] !== undefined) {
  41398. defines["LIGHT" + index] = false;
  41399. defines["HEMILIGHT" + lightIndex] = false;
  41400. defines["POINTLIGHT" + lightIndex] = false;
  41401. defines["DIRLIGHT" + lightIndex] = false;
  41402. defines["SPOTLIGHT" + lightIndex] = false;
  41403. defines["SHADOW" + lightIndex] = false;
  41404. }
  41405. }
  41406. var caps = scene.getEngine().getCaps();
  41407. if (defines["SHADOWFLOAT"] === undefined) {
  41408. needRebuild = true;
  41409. }
  41410. defines["SHADOWFLOAT"] = shadowEnabled &&
  41411. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41412. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41413. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41414. if (needRebuild) {
  41415. defines.rebuild();
  41416. }
  41417. return needNormals;
  41418. };
  41419. /**
  41420. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41421. * that won t be acctive due to defines being turned off.
  41422. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41423. * @param samplersList The samplers list
  41424. * @param defines The defines helping in the list generation
  41425. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41426. */
  41427. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41428. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41429. var uniformsList;
  41430. var uniformBuffersList = null;
  41431. if (uniformsListOrOptions.uniformsNames) {
  41432. var options = uniformsListOrOptions;
  41433. uniformsList = options.uniformsNames;
  41434. uniformBuffersList = options.uniformBuffersNames;
  41435. samplersList = options.samplers;
  41436. defines = options.defines;
  41437. maxSimultaneousLights = options.maxSimultaneousLights;
  41438. }
  41439. else {
  41440. uniformsList = uniformsListOrOptions;
  41441. if (!samplersList) {
  41442. samplersList = [];
  41443. }
  41444. }
  41445. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41446. if (!defines["LIGHT" + lightIndex]) {
  41447. break;
  41448. }
  41449. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41450. if (uniformBuffersList) {
  41451. uniformBuffersList.push("Light" + lightIndex);
  41452. }
  41453. samplersList.push("shadowSampler" + lightIndex);
  41454. samplersList.push("depthSampler" + lightIndex);
  41455. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41456. samplersList.push("projectionLightSampler" + lightIndex);
  41457. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41458. }
  41459. }
  41460. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41461. uniformsList.push("morphTargetInfluences");
  41462. }
  41463. };
  41464. /**
  41465. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41466. * @param defines The defines to update while falling back
  41467. * @param fallbacks The authorized effect fallbacks
  41468. * @param maxSimultaneousLights The maximum number of lights allowed
  41469. * @param rank the current rank of the Effect
  41470. * @returns The newly affected rank
  41471. */
  41472. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41473. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41474. if (rank === void 0) { rank = 0; }
  41475. var lightFallbackRank = 0;
  41476. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41477. if (!defines["LIGHT" + lightIndex]) {
  41478. break;
  41479. }
  41480. if (lightIndex > 0) {
  41481. lightFallbackRank = rank + lightIndex;
  41482. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41483. }
  41484. if (!defines["SHADOWS"]) {
  41485. if (defines["SHADOW" + lightIndex]) {
  41486. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41487. }
  41488. if (defines["SHADOWPCF" + lightIndex]) {
  41489. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41490. }
  41491. if (defines["SHADOWPCSS" + lightIndex]) {
  41492. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41493. }
  41494. if (defines["SHADOWPOISSON" + lightIndex]) {
  41495. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41496. }
  41497. if (defines["SHADOWESM" + lightIndex]) {
  41498. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41499. }
  41500. }
  41501. }
  41502. return lightFallbackRank++;
  41503. };
  41504. /**
  41505. * Prepares the list of attributes required for morph targets according to the effect defines.
  41506. * @param attribs The current list of supported attribs
  41507. * @param mesh The mesh to prepare the morph targets attributes for
  41508. * @param defines The current Defines of the effect
  41509. */
  41510. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41511. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41512. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41513. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41514. var manager = mesh.morphTargetManager;
  41515. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41516. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41517. for (var index = 0; index < influencers; index++) {
  41518. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41519. if (normal) {
  41520. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41521. }
  41522. if (tangent) {
  41523. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41524. }
  41525. if (attribs.length > maxAttributesCount) {
  41526. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41527. }
  41528. }
  41529. }
  41530. };
  41531. /**
  41532. * Prepares the list of attributes required for bones according to the effect defines.
  41533. * @param attribs The current list of supported attribs
  41534. * @param mesh The mesh to prepare the bones attributes for
  41535. * @param defines The current Defines of the effect
  41536. * @param fallbacks The current efffect fallback strategy
  41537. */
  41538. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41539. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41540. fallbacks.addCPUSkinningFallback(0, mesh);
  41541. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41542. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41543. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41544. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41545. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41546. }
  41547. }
  41548. };
  41549. /**
  41550. * Prepares the list of attributes required for instances according to the effect defines.
  41551. * @param attribs The current list of supported attribs
  41552. * @param defines The current Defines of the effect
  41553. */
  41554. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41555. if (defines["INSTANCES"]) {
  41556. attribs.push("world0");
  41557. attribs.push("world1");
  41558. attribs.push("world2");
  41559. attribs.push("world3");
  41560. }
  41561. };
  41562. /**
  41563. * Binds the light shadow information to the effect for the given mesh.
  41564. * @param light The light containing the generator
  41565. * @param scene The scene the lights belongs to
  41566. * @param mesh The mesh we are binding the information to render
  41567. * @param lightIndex The light index in the effect used to render the mesh
  41568. * @param effect The effect we are binding the data to
  41569. */
  41570. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41571. if (light.shadowEnabled && mesh.receiveShadows) {
  41572. var shadowGenerator = light.getShadowGenerator();
  41573. if (shadowGenerator) {
  41574. shadowGenerator.bindShadowLight(lightIndex, effect);
  41575. }
  41576. }
  41577. };
  41578. /**
  41579. * Binds the light information to the effect.
  41580. * @param light The light containing the generator
  41581. * @param effect The effect we are binding the data to
  41582. * @param lightIndex The light index in the effect used to render
  41583. */
  41584. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41585. light.transferToEffect(effect, lightIndex + "");
  41586. };
  41587. /**
  41588. * Binds the lights information from the scene to the effect for the given mesh.
  41589. * @param scene The scene the lights belongs to
  41590. * @param mesh The mesh we are binding the information to render
  41591. * @param effect The effect we are binding the data to
  41592. * @param defines The generated defines for the effect
  41593. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41594. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41595. */
  41596. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41597. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41598. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41599. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41600. for (var i = 0; i < len; i++) {
  41601. var light = mesh._lightSources[i];
  41602. var iAsString = i.toString();
  41603. var scaledIntensity = light.getScaledIntensity();
  41604. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41605. MaterialHelper.BindLightProperties(light, effect, i);
  41606. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41607. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41608. if (defines["SPECULARTERM"]) {
  41609. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41610. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41611. }
  41612. // Shadows
  41613. if (scene.shadowsEnabled) {
  41614. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41615. }
  41616. light._uniformBuffer.update();
  41617. }
  41618. };
  41619. /**
  41620. * Binds the fog information from the scene to the effect for the given mesh.
  41621. * @param scene The scene the lights belongs to
  41622. * @param mesh The mesh we are binding the information to render
  41623. * @param effect The effect we are binding the data to
  41624. */
  41625. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41626. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41627. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41628. effect.setColor3("vFogColor", scene.fogColor);
  41629. }
  41630. };
  41631. /**
  41632. * Binds the bones information from the mesh to the effect.
  41633. * @param mesh The mesh we are binding the information to render
  41634. * @param effect The effect we are binding the data to
  41635. */
  41636. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41637. if (!effect || !mesh) {
  41638. return;
  41639. }
  41640. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41641. mesh.computeBonesUsingShaders = false;
  41642. }
  41643. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41644. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41645. if (matrices) {
  41646. effect.setMatrices("mBones", matrices);
  41647. }
  41648. }
  41649. };
  41650. /**
  41651. * Binds the morph targets information from the mesh to the effect.
  41652. * @param abstractMesh The mesh we are binding the information to render
  41653. * @param effect The effect we are binding the data to
  41654. */
  41655. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41656. var manager = abstractMesh.morphTargetManager;
  41657. if (!abstractMesh || !manager) {
  41658. return;
  41659. }
  41660. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41661. };
  41662. /**
  41663. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41664. * @param defines The generated defines used in the effect
  41665. * @param effect The effect we are binding the data to
  41666. * @param scene The scene we are willing to render with logarithmic scale for
  41667. */
  41668. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41669. if (defines["LOGARITHMICDEPTH"]) {
  41670. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41671. }
  41672. };
  41673. /**
  41674. * Binds the clip plane information from the scene to the effect.
  41675. * @param scene The scene the clip plane information are extracted from
  41676. * @param effect The effect we are binding the data to
  41677. */
  41678. MaterialHelper.BindClipPlane = function (effect, scene) {
  41679. if (scene.clipPlane) {
  41680. var clipPlane = scene.clipPlane;
  41681. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41682. }
  41683. };
  41684. return MaterialHelper;
  41685. }());
  41686. BABYLON.MaterialHelper = MaterialHelper;
  41687. })(BABYLON || (BABYLON = {}));
  41688. //# sourceMappingURL=babylon.materialHelper.js.map
  41689. var BABYLON;
  41690. (function (BABYLON) {
  41691. var PushMaterial = /** @class */ (function (_super) {
  41692. __extends(PushMaterial, _super);
  41693. function PushMaterial(name, scene) {
  41694. var _this = _super.call(this, name, scene) || this;
  41695. _this._normalMatrix = new BABYLON.Matrix();
  41696. _this.storeEffectOnSubMeshes = true;
  41697. return _this;
  41698. }
  41699. PushMaterial.prototype.getEffect = function () {
  41700. return this._activeEffect;
  41701. };
  41702. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41703. if (!mesh) {
  41704. return false;
  41705. }
  41706. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41707. return true;
  41708. }
  41709. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41710. };
  41711. /**
  41712. * Binds the given world matrix to the active effect
  41713. *
  41714. * @param world the matrix to bind
  41715. */
  41716. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41717. this._activeEffect.setMatrix("world", world);
  41718. };
  41719. /**
  41720. * Binds the given normal matrix to the active effect
  41721. *
  41722. * @param normalMatrix the matrix to bind
  41723. */
  41724. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41725. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41726. };
  41727. PushMaterial.prototype.bind = function (world, mesh) {
  41728. if (!mesh) {
  41729. return;
  41730. }
  41731. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41732. };
  41733. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41734. if (effect === void 0) { effect = null; }
  41735. _super.prototype._afterBind.call(this, mesh);
  41736. this.getScene()._cachedEffect = effect;
  41737. };
  41738. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41739. if (visibility === void 0) { visibility = 1; }
  41740. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41741. };
  41742. return PushMaterial;
  41743. }(BABYLON.Material));
  41744. BABYLON.PushMaterial = PushMaterial;
  41745. })(BABYLON || (BABYLON = {}));
  41746. //# sourceMappingURL=babylon.pushMaterial.js.map
  41747. var BABYLON;
  41748. (function (BABYLON) {
  41749. /** @hidden */
  41750. var StandardMaterialDefines = /** @class */ (function (_super) {
  41751. __extends(StandardMaterialDefines, _super);
  41752. function StandardMaterialDefines() {
  41753. var _this = _super.call(this) || this;
  41754. _this.MAINUV1 = false;
  41755. _this.MAINUV2 = false;
  41756. _this.DIFFUSE = false;
  41757. _this.DIFFUSEDIRECTUV = 0;
  41758. _this.AMBIENT = false;
  41759. _this.AMBIENTDIRECTUV = 0;
  41760. _this.OPACITY = false;
  41761. _this.OPACITYDIRECTUV = 0;
  41762. _this.OPACITYRGB = false;
  41763. _this.REFLECTION = false;
  41764. _this.EMISSIVE = false;
  41765. _this.EMISSIVEDIRECTUV = 0;
  41766. _this.SPECULAR = false;
  41767. _this.SPECULARDIRECTUV = 0;
  41768. _this.BUMP = false;
  41769. _this.BUMPDIRECTUV = 0;
  41770. _this.PARALLAX = false;
  41771. _this.PARALLAXOCCLUSION = false;
  41772. _this.SPECULAROVERALPHA = false;
  41773. _this.CLIPPLANE = false;
  41774. _this.ALPHATEST = false;
  41775. _this.DEPTHPREPASS = false;
  41776. _this.ALPHAFROMDIFFUSE = false;
  41777. _this.POINTSIZE = false;
  41778. _this.FOG = false;
  41779. _this.SPECULARTERM = false;
  41780. _this.DIFFUSEFRESNEL = false;
  41781. _this.OPACITYFRESNEL = false;
  41782. _this.REFLECTIONFRESNEL = false;
  41783. _this.REFRACTIONFRESNEL = false;
  41784. _this.EMISSIVEFRESNEL = false;
  41785. _this.FRESNEL = false;
  41786. _this.NORMAL = false;
  41787. _this.UV1 = false;
  41788. _this.UV2 = false;
  41789. _this.VERTEXCOLOR = false;
  41790. _this.VERTEXALPHA = false;
  41791. _this.NUM_BONE_INFLUENCERS = 0;
  41792. _this.BonesPerMesh = 0;
  41793. _this.INSTANCES = false;
  41794. _this.GLOSSINESS = false;
  41795. _this.ROUGHNESS = false;
  41796. _this.EMISSIVEASILLUMINATION = false;
  41797. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41798. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41799. _this.LIGHTMAP = false;
  41800. _this.LIGHTMAPDIRECTUV = 0;
  41801. _this.OBJECTSPACE_NORMALMAP = false;
  41802. _this.USELIGHTMAPASSHADOWMAP = false;
  41803. _this.REFLECTIONMAP_3D = false;
  41804. _this.REFLECTIONMAP_SPHERICAL = false;
  41805. _this.REFLECTIONMAP_PLANAR = false;
  41806. _this.REFLECTIONMAP_CUBIC = false;
  41807. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41808. _this.REFLECTIONMAP_PROJECTION = false;
  41809. _this.REFLECTIONMAP_SKYBOX = false;
  41810. _this.REFLECTIONMAP_EXPLICIT = false;
  41811. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41812. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41813. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41814. _this.INVERTCUBICMAP = false;
  41815. _this.LOGARITHMICDEPTH = false;
  41816. _this.REFRACTION = false;
  41817. _this.REFRACTIONMAP_3D = false;
  41818. _this.REFLECTIONOVERALPHA = false;
  41819. _this.TWOSIDEDLIGHTING = false;
  41820. _this.SHADOWFLOAT = false;
  41821. _this.MORPHTARGETS = false;
  41822. _this.MORPHTARGETS_NORMAL = false;
  41823. _this.MORPHTARGETS_TANGENT = false;
  41824. _this.NUM_MORPH_INFLUENCERS = 0;
  41825. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41826. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41827. _this.IMAGEPROCESSING = false;
  41828. _this.VIGNETTE = false;
  41829. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41830. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41831. _this.TONEMAPPING = false;
  41832. _this.CONTRAST = false;
  41833. _this.COLORCURVES = false;
  41834. _this.COLORGRADING = false;
  41835. _this.COLORGRADING3D = false;
  41836. _this.SAMPLER3DGREENDEPTH = false;
  41837. _this.SAMPLER3DBGRMAP = false;
  41838. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41839. /**
  41840. * If the reflection texture on this material is in linear color space
  41841. * @hidden
  41842. */
  41843. _this.IS_REFLECTION_LINEAR = false;
  41844. /**
  41845. * If the refraction texture on this material is in linear color space
  41846. * @hidden
  41847. */
  41848. _this.IS_REFRACTION_LINEAR = false;
  41849. _this.EXPOSURE = false;
  41850. _this.rebuild();
  41851. return _this;
  41852. }
  41853. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41854. var modes = [
  41855. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41856. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41857. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41858. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41859. ];
  41860. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41861. var mode = modes_1[_i];
  41862. this[mode] = (mode === modeToEnable);
  41863. }
  41864. };
  41865. return StandardMaterialDefines;
  41866. }(BABYLON.MaterialDefines));
  41867. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41868. var StandardMaterial = /** @class */ (function (_super) {
  41869. __extends(StandardMaterial, _super);
  41870. function StandardMaterial(name, scene) {
  41871. var _this = _super.call(this, name, scene) || this;
  41872. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41873. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41874. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41875. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41876. _this.specularPower = 64;
  41877. _this._useAlphaFromDiffuseTexture = false;
  41878. _this._useEmissiveAsIllumination = false;
  41879. _this._linkEmissiveWithDiffuse = false;
  41880. _this._useSpecularOverAlpha = false;
  41881. _this._useReflectionOverAlpha = false;
  41882. _this._disableLighting = false;
  41883. _this._useObjectSpaceNormalMap = false;
  41884. _this._useParallax = false;
  41885. _this._useParallaxOcclusion = false;
  41886. _this.parallaxScaleBias = 0.05;
  41887. _this._roughness = 0;
  41888. _this.indexOfRefraction = 0.98;
  41889. _this.invertRefractionY = true;
  41890. /**
  41891. * Defines the alpha limits in alpha test mode
  41892. */
  41893. _this.alphaCutOff = 0.4;
  41894. _this._useLightmapAsShadowmap = false;
  41895. _this._useReflectionFresnelFromSpecular = false;
  41896. _this._useGlossinessFromSpecularMapAlpha = false;
  41897. _this._maxSimultaneousLights = 4;
  41898. /**
  41899. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41900. */
  41901. _this._invertNormalMapX = false;
  41902. /**
  41903. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41904. */
  41905. _this._invertNormalMapY = false;
  41906. /**
  41907. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41908. */
  41909. _this._twoSidedLighting = false;
  41910. _this._renderTargets = new BABYLON.SmartArray(16);
  41911. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41912. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41913. // Setup the default processing configuration to the scene.
  41914. _this._attachImageProcessingConfiguration(null);
  41915. _this.getRenderTargetTextures = function () {
  41916. _this._renderTargets.reset();
  41917. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41918. _this._renderTargets.push(_this._reflectionTexture);
  41919. }
  41920. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41921. _this._renderTargets.push(_this._refractionTexture);
  41922. }
  41923. return _this._renderTargets;
  41924. };
  41925. return _this;
  41926. }
  41927. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41928. /**
  41929. * Gets the image processing configuration used either in this material.
  41930. */
  41931. get: function () {
  41932. return this._imageProcessingConfiguration;
  41933. },
  41934. /**
  41935. * Sets the Default image processing configuration used either in the this material.
  41936. *
  41937. * If sets to null, the scene one is in use.
  41938. */
  41939. set: function (value) {
  41940. this._attachImageProcessingConfiguration(value);
  41941. // Ensure the effect will be rebuilt.
  41942. this._markAllSubMeshesAsTexturesDirty();
  41943. },
  41944. enumerable: true,
  41945. configurable: true
  41946. });
  41947. /**
  41948. * Attaches a new image processing configuration to the Standard Material.
  41949. * @param configuration
  41950. */
  41951. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41952. var _this = this;
  41953. if (configuration === this._imageProcessingConfiguration) {
  41954. return;
  41955. }
  41956. // Detaches observer.
  41957. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41958. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41959. }
  41960. // Pick the scene configuration if needed.
  41961. if (!configuration) {
  41962. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41963. }
  41964. else {
  41965. this._imageProcessingConfiguration = configuration;
  41966. }
  41967. // Attaches observer.
  41968. if (this._imageProcessingConfiguration) {
  41969. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41970. _this._markAllSubMeshesAsImageProcessingDirty();
  41971. });
  41972. }
  41973. };
  41974. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41975. /**
  41976. * Gets wether the color curves effect is enabled.
  41977. */
  41978. get: function () {
  41979. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41980. },
  41981. /**
  41982. * Sets wether the color curves effect is enabled.
  41983. */
  41984. set: function (value) {
  41985. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41986. },
  41987. enumerable: true,
  41988. configurable: true
  41989. });
  41990. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41991. /**
  41992. * Gets wether the color grading effect is enabled.
  41993. */
  41994. get: function () {
  41995. return this.imageProcessingConfiguration.colorGradingEnabled;
  41996. },
  41997. /**
  41998. * Gets wether the color grading effect is enabled.
  41999. */
  42000. set: function (value) {
  42001. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42002. },
  42003. enumerable: true,
  42004. configurable: true
  42005. });
  42006. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42007. /**
  42008. * Gets wether tonemapping is enabled or not.
  42009. */
  42010. get: function () {
  42011. return this._imageProcessingConfiguration.toneMappingEnabled;
  42012. },
  42013. /**
  42014. * Sets wether tonemapping is enabled or not
  42015. */
  42016. set: function (value) {
  42017. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42018. },
  42019. enumerable: true,
  42020. configurable: true
  42021. });
  42022. ;
  42023. ;
  42024. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42025. /**
  42026. * The camera exposure used on this material.
  42027. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42028. * This corresponds to a photographic exposure.
  42029. */
  42030. get: function () {
  42031. return this._imageProcessingConfiguration.exposure;
  42032. },
  42033. /**
  42034. * The camera exposure used on this material.
  42035. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42036. * This corresponds to a photographic exposure.
  42037. */
  42038. set: function (value) {
  42039. this._imageProcessingConfiguration.exposure = value;
  42040. },
  42041. enumerable: true,
  42042. configurable: true
  42043. });
  42044. ;
  42045. ;
  42046. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42047. /**
  42048. * Gets The camera contrast used on this material.
  42049. */
  42050. get: function () {
  42051. return this._imageProcessingConfiguration.contrast;
  42052. },
  42053. /**
  42054. * Sets The camera contrast used on this material.
  42055. */
  42056. set: function (value) {
  42057. this._imageProcessingConfiguration.contrast = value;
  42058. },
  42059. enumerable: true,
  42060. configurable: true
  42061. });
  42062. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42063. /**
  42064. * Gets the Color Grading 2D Lookup Texture.
  42065. */
  42066. get: function () {
  42067. return this._imageProcessingConfiguration.colorGradingTexture;
  42068. },
  42069. /**
  42070. * Sets the Color Grading 2D Lookup Texture.
  42071. */
  42072. set: function (value) {
  42073. this._imageProcessingConfiguration.colorGradingTexture = value;
  42074. },
  42075. enumerable: true,
  42076. configurable: true
  42077. });
  42078. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42079. /**
  42080. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42081. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42082. * 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;
  42083. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42084. */
  42085. get: function () {
  42086. return this._imageProcessingConfiguration.colorCurves;
  42087. },
  42088. /**
  42089. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42090. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42091. * 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;
  42092. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42093. */
  42094. set: function (value) {
  42095. this._imageProcessingConfiguration.colorCurves = value;
  42096. },
  42097. enumerable: true,
  42098. configurable: true
  42099. });
  42100. StandardMaterial.prototype.getClassName = function () {
  42101. return "StandardMaterial";
  42102. };
  42103. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42104. get: function () {
  42105. return this._useLogarithmicDepth;
  42106. },
  42107. set: function (value) {
  42108. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42109. this._markAllSubMeshesAsMiscDirty();
  42110. },
  42111. enumerable: true,
  42112. configurable: true
  42113. });
  42114. StandardMaterial.prototype.needAlphaBlending = function () {
  42115. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42116. };
  42117. StandardMaterial.prototype.needAlphaTesting = function () {
  42118. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42119. };
  42120. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42121. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42122. };
  42123. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42124. return this._diffuseTexture;
  42125. };
  42126. /**
  42127. * Child classes can use it to update shaders
  42128. */
  42129. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42130. if (useInstances === void 0) { useInstances = false; }
  42131. if (subMesh.effect && this.isFrozen) {
  42132. if (this._wasPreviouslyReady && subMesh.effect) {
  42133. return true;
  42134. }
  42135. }
  42136. if (!subMesh._materialDefines) {
  42137. subMesh._materialDefines = new StandardMaterialDefines();
  42138. }
  42139. var scene = this.getScene();
  42140. var defines = subMesh._materialDefines;
  42141. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42142. if (defines._renderId === scene.getRenderId()) {
  42143. return true;
  42144. }
  42145. }
  42146. var engine = scene.getEngine();
  42147. // Lights
  42148. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42149. // Textures
  42150. if (defines._areTexturesDirty) {
  42151. defines._needUVs = false;
  42152. defines.MAINUV1 = false;
  42153. defines.MAINUV2 = false;
  42154. if (scene.texturesEnabled) {
  42155. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42156. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42157. return false;
  42158. }
  42159. else {
  42160. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42161. }
  42162. }
  42163. else {
  42164. defines.DIFFUSE = false;
  42165. }
  42166. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42167. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42168. return false;
  42169. }
  42170. else {
  42171. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42172. }
  42173. }
  42174. else {
  42175. defines.AMBIENT = false;
  42176. }
  42177. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42178. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42179. return false;
  42180. }
  42181. else {
  42182. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42183. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42184. }
  42185. }
  42186. else {
  42187. defines.OPACITY = false;
  42188. }
  42189. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42190. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42191. return false;
  42192. }
  42193. else {
  42194. defines._needNormals = true;
  42195. defines.REFLECTION = true;
  42196. defines.ROUGHNESS = (this._roughness > 0);
  42197. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42198. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42199. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42200. switch (this._reflectionTexture.coordinatesMode) {
  42201. case BABYLON.Texture.EXPLICIT_MODE:
  42202. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42203. break;
  42204. case BABYLON.Texture.PLANAR_MODE:
  42205. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42206. break;
  42207. case BABYLON.Texture.PROJECTION_MODE:
  42208. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42209. break;
  42210. case BABYLON.Texture.SKYBOX_MODE:
  42211. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42212. break;
  42213. case BABYLON.Texture.SPHERICAL_MODE:
  42214. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42215. break;
  42216. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42217. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42218. break;
  42219. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42220. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42221. break;
  42222. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42223. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42224. break;
  42225. case BABYLON.Texture.CUBIC_MODE:
  42226. case BABYLON.Texture.INVCUBIC_MODE:
  42227. default:
  42228. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42229. break;
  42230. }
  42231. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42232. }
  42233. }
  42234. else {
  42235. defines.REFLECTION = false;
  42236. }
  42237. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42238. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42239. return false;
  42240. }
  42241. else {
  42242. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42243. }
  42244. }
  42245. else {
  42246. defines.EMISSIVE = false;
  42247. }
  42248. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42249. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42250. return false;
  42251. }
  42252. else {
  42253. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42254. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42255. }
  42256. }
  42257. else {
  42258. defines.LIGHTMAP = false;
  42259. }
  42260. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42261. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42262. return false;
  42263. }
  42264. else {
  42265. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42266. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42267. }
  42268. }
  42269. else {
  42270. defines.SPECULAR = false;
  42271. }
  42272. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42273. // Bump texure can not be not blocking.
  42274. if (!this._bumpTexture.isReady()) {
  42275. return false;
  42276. }
  42277. else {
  42278. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42279. defines.PARALLAX = this._useParallax;
  42280. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42281. }
  42282. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42283. }
  42284. else {
  42285. defines.BUMP = false;
  42286. }
  42287. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42288. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42289. return false;
  42290. }
  42291. else {
  42292. defines._needUVs = true;
  42293. defines.REFRACTION = true;
  42294. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42295. }
  42296. }
  42297. else {
  42298. defines.REFRACTION = false;
  42299. }
  42300. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42301. }
  42302. else {
  42303. defines.DIFFUSE = false;
  42304. defines.AMBIENT = false;
  42305. defines.OPACITY = false;
  42306. defines.REFLECTION = false;
  42307. defines.EMISSIVE = false;
  42308. defines.LIGHTMAP = false;
  42309. defines.BUMP = false;
  42310. defines.REFRACTION = false;
  42311. }
  42312. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42313. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42314. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42315. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42316. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42317. }
  42318. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42319. if (!this._imageProcessingConfiguration.isReady()) {
  42320. return false;
  42321. }
  42322. this._imageProcessingConfiguration.prepareDefines(defines);
  42323. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42324. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42325. }
  42326. if (defines._areFresnelDirty) {
  42327. if (StandardMaterial.FresnelEnabled) {
  42328. // Fresnel
  42329. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42330. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42331. this._reflectionFresnelParameters) {
  42332. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42333. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42334. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42335. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42336. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42337. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42338. defines._needNormals = true;
  42339. defines.FRESNEL = true;
  42340. }
  42341. }
  42342. else {
  42343. defines.FRESNEL = false;
  42344. }
  42345. }
  42346. // Misc.
  42347. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42348. // Attribs
  42349. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42350. // Values that need to be evaluated on every frame
  42351. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42352. // Get correct effect
  42353. if (defines.isDirty) {
  42354. defines.markAsProcessed();
  42355. scene.resetCachedMaterial();
  42356. // Fallbacks
  42357. var fallbacks = new BABYLON.EffectFallbacks();
  42358. if (defines.REFLECTION) {
  42359. fallbacks.addFallback(0, "REFLECTION");
  42360. }
  42361. if (defines.SPECULAR) {
  42362. fallbacks.addFallback(0, "SPECULAR");
  42363. }
  42364. if (defines.BUMP) {
  42365. fallbacks.addFallback(0, "BUMP");
  42366. }
  42367. if (defines.PARALLAX) {
  42368. fallbacks.addFallback(1, "PARALLAX");
  42369. }
  42370. if (defines.PARALLAXOCCLUSION) {
  42371. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42372. }
  42373. if (defines.SPECULAROVERALPHA) {
  42374. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42375. }
  42376. if (defines.FOG) {
  42377. fallbacks.addFallback(1, "FOG");
  42378. }
  42379. if (defines.POINTSIZE) {
  42380. fallbacks.addFallback(0, "POINTSIZE");
  42381. }
  42382. if (defines.LOGARITHMICDEPTH) {
  42383. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42384. }
  42385. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42386. if (defines.SPECULARTERM) {
  42387. fallbacks.addFallback(0, "SPECULARTERM");
  42388. }
  42389. if (defines.DIFFUSEFRESNEL) {
  42390. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42391. }
  42392. if (defines.OPACITYFRESNEL) {
  42393. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42394. }
  42395. if (defines.REFLECTIONFRESNEL) {
  42396. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42397. }
  42398. if (defines.EMISSIVEFRESNEL) {
  42399. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42400. }
  42401. if (defines.FRESNEL) {
  42402. fallbacks.addFallback(4, "FRESNEL");
  42403. }
  42404. //Attributes
  42405. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42406. if (defines.NORMAL) {
  42407. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42408. }
  42409. if (defines.UV1) {
  42410. attribs.push(BABYLON.VertexBuffer.UVKind);
  42411. }
  42412. if (defines.UV2) {
  42413. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42414. }
  42415. if (defines.VERTEXCOLOR) {
  42416. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42417. }
  42418. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42419. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42420. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42421. var shaderName = "default";
  42422. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42423. "vFogInfos", "vFogColor", "pointSize",
  42424. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42425. "mBones",
  42426. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42427. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42428. "vReflectionPosition", "vReflectionSize",
  42429. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42430. ];
  42431. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42432. var uniformBuffers = ["Material", "Scene"];
  42433. if (BABYLON.ImageProcessingConfiguration) {
  42434. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42435. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42436. }
  42437. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42438. uniformsNames: uniforms,
  42439. uniformBuffersNames: uniformBuffers,
  42440. samplers: samplers,
  42441. defines: defines,
  42442. maxSimultaneousLights: this._maxSimultaneousLights
  42443. });
  42444. if (this.customShaderNameResolve) {
  42445. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42446. }
  42447. var join = defines.toString();
  42448. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42449. attributes: attribs,
  42450. uniformsNames: uniforms,
  42451. uniformBuffersNames: uniformBuffers,
  42452. samplers: samplers,
  42453. defines: join,
  42454. fallbacks: fallbacks,
  42455. onCompiled: this.onCompiled,
  42456. onError: this.onError,
  42457. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42458. }, engine), defines);
  42459. this.buildUniformLayout();
  42460. }
  42461. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42462. return false;
  42463. }
  42464. defines._renderId = scene.getRenderId();
  42465. this._wasPreviouslyReady = true;
  42466. return true;
  42467. };
  42468. StandardMaterial.prototype.buildUniformLayout = function () {
  42469. // Order is important !
  42470. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42471. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42472. this._uniformBuffer.addUniform("opacityParts", 4);
  42473. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42474. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42475. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42476. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42477. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42478. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42479. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42480. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42481. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42482. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42483. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42484. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42485. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42486. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42487. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42488. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42489. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42490. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42491. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42492. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42493. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42494. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42495. this._uniformBuffer.addUniform("specularMatrix", 16);
  42496. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42497. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42498. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42499. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42500. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42501. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42502. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42503. this._uniformBuffer.addUniform("pointSize", 1);
  42504. this._uniformBuffer.create();
  42505. };
  42506. StandardMaterial.prototype.unbind = function () {
  42507. if (this._activeEffect) {
  42508. var needFlag = false;
  42509. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42510. this._activeEffect.setTexture("reflection2DSampler", null);
  42511. needFlag = true;
  42512. }
  42513. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42514. this._activeEffect.setTexture("refraction2DSampler", null);
  42515. needFlag = true;
  42516. }
  42517. if (needFlag) {
  42518. this._markAllSubMeshesAsTexturesDirty();
  42519. }
  42520. }
  42521. _super.prototype.unbind.call(this);
  42522. };
  42523. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42524. var scene = this.getScene();
  42525. var defines = subMesh._materialDefines;
  42526. if (!defines) {
  42527. return;
  42528. }
  42529. var effect = subMesh.effect;
  42530. if (!effect) {
  42531. return;
  42532. }
  42533. this._activeEffect = effect;
  42534. // Matrices
  42535. this.bindOnlyWorldMatrix(world);
  42536. // Normal Matrix
  42537. if (defines.OBJECTSPACE_NORMALMAP) {
  42538. world.toNormalMatrix(this._normalMatrix);
  42539. this.bindOnlyNormalMatrix(this._normalMatrix);
  42540. }
  42541. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42542. // Bones
  42543. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42544. if (mustRebind) {
  42545. this._uniformBuffer.bindToEffect(effect, "Material");
  42546. this.bindViewProjection(effect);
  42547. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42548. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42549. // Fresnel
  42550. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42551. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42552. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42553. }
  42554. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42555. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42556. }
  42557. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42558. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42559. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42560. }
  42561. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42562. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42563. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42564. }
  42565. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42566. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42567. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42568. }
  42569. }
  42570. // Textures
  42571. if (scene.texturesEnabled) {
  42572. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42573. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42574. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42575. if (this._diffuseTexture.hasAlpha) {
  42576. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42577. }
  42578. }
  42579. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42580. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42581. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42582. }
  42583. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42584. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42585. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42586. }
  42587. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42588. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42589. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42590. if (this._reflectionTexture.boundingBoxSize) {
  42591. var cubeTexture = this._reflectionTexture;
  42592. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42593. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42594. }
  42595. }
  42596. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42597. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42598. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42599. }
  42600. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42601. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42602. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42603. }
  42604. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42605. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42606. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42607. }
  42608. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42609. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42610. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42611. if (scene._mirroredCameraPosition) {
  42612. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42613. }
  42614. else {
  42615. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42616. }
  42617. }
  42618. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42619. var depth = 1.0;
  42620. if (!this._refractionTexture.isCube) {
  42621. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42622. if (this._refractionTexture.depth) {
  42623. depth = this._refractionTexture.depth;
  42624. }
  42625. }
  42626. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42627. }
  42628. }
  42629. // Point size
  42630. if (this.pointsCloud) {
  42631. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42632. }
  42633. if (defines.SPECULARTERM) {
  42634. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42635. }
  42636. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42637. // Diffuse
  42638. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42639. }
  42640. // Textures
  42641. if (scene.texturesEnabled) {
  42642. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42643. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42644. }
  42645. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42646. effect.setTexture("ambientSampler", this._ambientTexture);
  42647. }
  42648. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42649. effect.setTexture("opacitySampler", this._opacityTexture);
  42650. }
  42651. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42652. if (this._reflectionTexture.isCube) {
  42653. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42654. }
  42655. else {
  42656. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42657. }
  42658. }
  42659. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42660. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42661. }
  42662. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42663. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42664. }
  42665. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42666. effect.setTexture("specularSampler", this._specularTexture);
  42667. }
  42668. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42669. effect.setTexture("bumpSampler", this._bumpTexture);
  42670. }
  42671. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42672. var depth = 1.0;
  42673. if (this._refractionTexture.isCube) {
  42674. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42675. }
  42676. else {
  42677. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42678. }
  42679. }
  42680. }
  42681. // Clip plane
  42682. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42683. // Colors
  42684. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42685. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42686. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42687. }
  42688. if (mustRebind || !this.isFrozen) {
  42689. // Lights
  42690. if (scene.lightsEnabled && !this._disableLighting) {
  42691. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42692. }
  42693. // View
  42694. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42695. this.bindView(effect);
  42696. }
  42697. // Fog
  42698. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42699. // Morph targets
  42700. if (defines.NUM_MORPH_INFLUENCERS) {
  42701. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42702. }
  42703. // Log. depth
  42704. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42705. // image processing
  42706. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42707. this._imageProcessingConfiguration.bind(this._activeEffect);
  42708. }
  42709. }
  42710. this._uniformBuffer.update();
  42711. this._afterBind(mesh, this._activeEffect);
  42712. };
  42713. StandardMaterial.prototype.getAnimatables = function () {
  42714. var results = [];
  42715. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42716. results.push(this._diffuseTexture);
  42717. }
  42718. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42719. results.push(this._ambientTexture);
  42720. }
  42721. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42722. results.push(this._opacityTexture);
  42723. }
  42724. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42725. results.push(this._reflectionTexture);
  42726. }
  42727. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42728. results.push(this._emissiveTexture);
  42729. }
  42730. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42731. results.push(this._specularTexture);
  42732. }
  42733. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42734. results.push(this._bumpTexture);
  42735. }
  42736. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42737. results.push(this._lightmapTexture);
  42738. }
  42739. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42740. results.push(this._refractionTexture);
  42741. }
  42742. return results;
  42743. };
  42744. StandardMaterial.prototype.getActiveTextures = function () {
  42745. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42746. if (this._diffuseTexture) {
  42747. activeTextures.push(this._diffuseTexture);
  42748. }
  42749. if (this._ambientTexture) {
  42750. activeTextures.push(this._ambientTexture);
  42751. }
  42752. if (this._opacityTexture) {
  42753. activeTextures.push(this._opacityTexture);
  42754. }
  42755. if (this._reflectionTexture) {
  42756. activeTextures.push(this._reflectionTexture);
  42757. }
  42758. if (this._emissiveTexture) {
  42759. activeTextures.push(this._emissiveTexture);
  42760. }
  42761. if (this._specularTexture) {
  42762. activeTextures.push(this._specularTexture);
  42763. }
  42764. if (this._bumpTexture) {
  42765. activeTextures.push(this._bumpTexture);
  42766. }
  42767. if (this._lightmapTexture) {
  42768. activeTextures.push(this._lightmapTexture);
  42769. }
  42770. if (this._refractionTexture) {
  42771. activeTextures.push(this._refractionTexture);
  42772. }
  42773. return activeTextures;
  42774. };
  42775. StandardMaterial.prototype.hasTexture = function (texture) {
  42776. if (_super.prototype.hasTexture.call(this, texture)) {
  42777. return true;
  42778. }
  42779. if (this._diffuseTexture === texture) {
  42780. return true;
  42781. }
  42782. if (this._ambientTexture === texture) {
  42783. return true;
  42784. }
  42785. if (this._opacityTexture === texture) {
  42786. return true;
  42787. }
  42788. if (this._reflectionTexture === texture) {
  42789. return true;
  42790. }
  42791. if (this._emissiveTexture === texture) {
  42792. return true;
  42793. }
  42794. if (this._specularTexture === texture) {
  42795. return true;
  42796. }
  42797. if (this._bumpTexture === texture) {
  42798. return true;
  42799. }
  42800. if (this._lightmapTexture === texture) {
  42801. return true;
  42802. }
  42803. if (this._refractionTexture === texture) {
  42804. return true;
  42805. }
  42806. return false;
  42807. };
  42808. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42809. if (forceDisposeTextures) {
  42810. if (this._diffuseTexture) {
  42811. this._diffuseTexture.dispose();
  42812. }
  42813. if (this._ambientTexture) {
  42814. this._ambientTexture.dispose();
  42815. }
  42816. if (this._opacityTexture) {
  42817. this._opacityTexture.dispose();
  42818. }
  42819. if (this._reflectionTexture) {
  42820. this._reflectionTexture.dispose();
  42821. }
  42822. if (this._emissiveTexture) {
  42823. this._emissiveTexture.dispose();
  42824. }
  42825. if (this._specularTexture) {
  42826. this._specularTexture.dispose();
  42827. }
  42828. if (this._bumpTexture) {
  42829. this._bumpTexture.dispose();
  42830. }
  42831. if (this._lightmapTexture) {
  42832. this._lightmapTexture.dispose();
  42833. }
  42834. if (this._refractionTexture) {
  42835. this._refractionTexture.dispose();
  42836. }
  42837. }
  42838. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42839. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42840. }
  42841. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42842. };
  42843. StandardMaterial.prototype.clone = function (name) {
  42844. var _this = this;
  42845. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42846. result.name = name;
  42847. result.id = name;
  42848. return result;
  42849. };
  42850. StandardMaterial.prototype.serialize = function () {
  42851. return BABYLON.SerializationHelper.Serialize(this);
  42852. };
  42853. // Statics
  42854. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42855. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42856. };
  42857. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42858. get: function () {
  42859. return StandardMaterial._DiffuseTextureEnabled;
  42860. },
  42861. set: function (value) {
  42862. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42863. return;
  42864. }
  42865. StandardMaterial._DiffuseTextureEnabled = value;
  42866. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42867. },
  42868. enumerable: true,
  42869. configurable: true
  42870. });
  42871. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42872. get: function () {
  42873. return StandardMaterial._AmbientTextureEnabled;
  42874. },
  42875. set: function (value) {
  42876. if (StandardMaterial._AmbientTextureEnabled === value) {
  42877. return;
  42878. }
  42879. StandardMaterial._AmbientTextureEnabled = value;
  42880. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42881. },
  42882. enumerable: true,
  42883. configurable: true
  42884. });
  42885. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42886. get: function () {
  42887. return StandardMaterial._OpacityTextureEnabled;
  42888. },
  42889. set: function (value) {
  42890. if (StandardMaterial._OpacityTextureEnabled === value) {
  42891. return;
  42892. }
  42893. StandardMaterial._OpacityTextureEnabled = value;
  42894. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42895. },
  42896. enumerable: true,
  42897. configurable: true
  42898. });
  42899. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42900. get: function () {
  42901. return StandardMaterial._ReflectionTextureEnabled;
  42902. },
  42903. set: function (value) {
  42904. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42905. return;
  42906. }
  42907. StandardMaterial._ReflectionTextureEnabled = value;
  42908. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42909. },
  42910. enumerable: true,
  42911. configurable: true
  42912. });
  42913. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42914. get: function () {
  42915. return StandardMaterial._EmissiveTextureEnabled;
  42916. },
  42917. set: function (value) {
  42918. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42919. return;
  42920. }
  42921. StandardMaterial._EmissiveTextureEnabled = value;
  42922. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42923. },
  42924. enumerable: true,
  42925. configurable: true
  42926. });
  42927. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42928. get: function () {
  42929. return StandardMaterial._SpecularTextureEnabled;
  42930. },
  42931. set: function (value) {
  42932. if (StandardMaterial._SpecularTextureEnabled === value) {
  42933. return;
  42934. }
  42935. StandardMaterial._SpecularTextureEnabled = value;
  42936. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42937. },
  42938. enumerable: true,
  42939. configurable: true
  42940. });
  42941. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42942. get: function () {
  42943. return StandardMaterial._BumpTextureEnabled;
  42944. },
  42945. set: function (value) {
  42946. if (StandardMaterial._BumpTextureEnabled === value) {
  42947. return;
  42948. }
  42949. StandardMaterial._BumpTextureEnabled = value;
  42950. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42951. },
  42952. enumerable: true,
  42953. configurable: true
  42954. });
  42955. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42956. get: function () {
  42957. return StandardMaterial._LightmapTextureEnabled;
  42958. },
  42959. set: function (value) {
  42960. if (StandardMaterial._LightmapTextureEnabled === value) {
  42961. return;
  42962. }
  42963. StandardMaterial._LightmapTextureEnabled = value;
  42964. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42965. },
  42966. enumerable: true,
  42967. configurable: true
  42968. });
  42969. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42970. get: function () {
  42971. return StandardMaterial._RefractionTextureEnabled;
  42972. },
  42973. set: function (value) {
  42974. if (StandardMaterial._RefractionTextureEnabled === value) {
  42975. return;
  42976. }
  42977. StandardMaterial._RefractionTextureEnabled = value;
  42978. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42979. },
  42980. enumerable: true,
  42981. configurable: true
  42982. });
  42983. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42984. get: function () {
  42985. return StandardMaterial._ColorGradingTextureEnabled;
  42986. },
  42987. set: function (value) {
  42988. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42989. return;
  42990. }
  42991. StandardMaterial._ColorGradingTextureEnabled = value;
  42992. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42993. },
  42994. enumerable: true,
  42995. configurable: true
  42996. });
  42997. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42998. get: function () {
  42999. return StandardMaterial._FresnelEnabled;
  43000. },
  43001. set: function (value) {
  43002. if (StandardMaterial._FresnelEnabled === value) {
  43003. return;
  43004. }
  43005. StandardMaterial._FresnelEnabled = value;
  43006. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43007. },
  43008. enumerable: true,
  43009. configurable: true
  43010. });
  43011. // Flags used to enable or disable a type of texture for all Standard Materials
  43012. StandardMaterial._DiffuseTextureEnabled = true;
  43013. StandardMaterial._AmbientTextureEnabled = true;
  43014. StandardMaterial._OpacityTextureEnabled = true;
  43015. StandardMaterial._ReflectionTextureEnabled = true;
  43016. StandardMaterial._EmissiveTextureEnabled = true;
  43017. StandardMaterial._SpecularTextureEnabled = true;
  43018. StandardMaterial._BumpTextureEnabled = true;
  43019. StandardMaterial._LightmapTextureEnabled = true;
  43020. StandardMaterial._RefractionTextureEnabled = true;
  43021. StandardMaterial._ColorGradingTextureEnabled = true;
  43022. StandardMaterial._FresnelEnabled = true;
  43023. __decorate([
  43024. BABYLON.serializeAsTexture("diffuseTexture")
  43025. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43026. __decorate([
  43027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43028. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43029. __decorate([
  43030. BABYLON.serializeAsTexture("ambientTexture")
  43031. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43032. __decorate([
  43033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43034. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43035. __decorate([
  43036. BABYLON.serializeAsTexture("opacityTexture")
  43037. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43038. __decorate([
  43039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43040. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43041. __decorate([
  43042. BABYLON.serializeAsTexture("reflectionTexture")
  43043. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43044. __decorate([
  43045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43046. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43047. __decorate([
  43048. BABYLON.serializeAsTexture("emissiveTexture")
  43049. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43050. __decorate([
  43051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43052. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43053. __decorate([
  43054. BABYLON.serializeAsTexture("specularTexture")
  43055. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43056. __decorate([
  43057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43058. ], StandardMaterial.prototype, "specularTexture", void 0);
  43059. __decorate([
  43060. BABYLON.serializeAsTexture("bumpTexture")
  43061. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43062. __decorate([
  43063. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43064. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43065. __decorate([
  43066. BABYLON.serializeAsTexture("lightmapTexture")
  43067. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43068. __decorate([
  43069. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43070. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43071. __decorate([
  43072. BABYLON.serializeAsTexture("refractionTexture")
  43073. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43074. __decorate([
  43075. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43076. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43077. __decorate([
  43078. BABYLON.serializeAsColor3("ambient")
  43079. ], StandardMaterial.prototype, "ambientColor", void 0);
  43080. __decorate([
  43081. BABYLON.serializeAsColor3("diffuse")
  43082. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43083. __decorate([
  43084. BABYLON.serializeAsColor3("specular")
  43085. ], StandardMaterial.prototype, "specularColor", void 0);
  43086. __decorate([
  43087. BABYLON.serializeAsColor3("emissive")
  43088. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43089. __decorate([
  43090. BABYLON.serialize()
  43091. ], StandardMaterial.prototype, "specularPower", void 0);
  43092. __decorate([
  43093. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43094. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43095. __decorate([
  43096. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43097. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43098. __decorate([
  43099. BABYLON.serialize("useEmissiveAsIllumination")
  43100. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43101. __decorate([
  43102. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43103. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43104. __decorate([
  43105. BABYLON.serialize("linkEmissiveWithDiffuse")
  43106. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43107. __decorate([
  43108. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43109. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43110. __decorate([
  43111. BABYLON.serialize("useSpecularOverAlpha")
  43112. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43113. __decorate([
  43114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43115. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43116. __decorate([
  43117. BABYLON.serialize("useReflectionOverAlpha")
  43118. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43119. __decorate([
  43120. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43121. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43122. __decorate([
  43123. BABYLON.serialize("disableLighting")
  43124. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43125. __decorate([
  43126. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43127. ], StandardMaterial.prototype, "disableLighting", void 0);
  43128. __decorate([
  43129. BABYLON.serialize("useObjectSpaceNormalMap")
  43130. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43131. __decorate([
  43132. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43133. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43134. __decorate([
  43135. BABYLON.serialize("useParallax")
  43136. ], StandardMaterial.prototype, "_useParallax", void 0);
  43137. __decorate([
  43138. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43139. ], StandardMaterial.prototype, "useParallax", void 0);
  43140. __decorate([
  43141. BABYLON.serialize("useParallaxOcclusion")
  43142. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43143. __decorate([
  43144. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43145. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43146. __decorate([
  43147. BABYLON.serialize()
  43148. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43149. __decorate([
  43150. BABYLON.serialize("roughness")
  43151. ], StandardMaterial.prototype, "_roughness", void 0);
  43152. __decorate([
  43153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43154. ], StandardMaterial.prototype, "roughness", void 0);
  43155. __decorate([
  43156. BABYLON.serialize()
  43157. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43158. __decorate([
  43159. BABYLON.serialize()
  43160. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43161. __decorate([
  43162. BABYLON.serialize()
  43163. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43164. __decorate([
  43165. BABYLON.serialize("useLightmapAsShadowmap")
  43166. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43167. __decorate([
  43168. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43169. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43170. __decorate([
  43171. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43172. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43173. __decorate([
  43174. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43175. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43176. __decorate([
  43177. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43178. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43179. __decorate([
  43180. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43181. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43182. __decorate([
  43183. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43184. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43185. __decorate([
  43186. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43187. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43188. __decorate([
  43189. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43190. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43191. __decorate([
  43192. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43193. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43194. __decorate([
  43195. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43196. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43197. __decorate([
  43198. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43199. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43200. __decorate([
  43201. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43202. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43203. __decorate([
  43204. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43205. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43206. __decorate([
  43207. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43208. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43209. __decorate([
  43210. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43211. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43212. __decorate([
  43213. BABYLON.serialize("maxSimultaneousLights")
  43214. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43215. __decorate([
  43216. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43217. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43218. __decorate([
  43219. BABYLON.serialize("invertNormalMapX")
  43220. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43221. __decorate([
  43222. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43223. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43224. __decorate([
  43225. BABYLON.serialize("invertNormalMapY")
  43226. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43227. __decorate([
  43228. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43229. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43230. __decorate([
  43231. BABYLON.serialize("twoSidedLighting")
  43232. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43233. __decorate([
  43234. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43235. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43236. __decorate([
  43237. BABYLON.serialize()
  43238. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43239. return StandardMaterial;
  43240. }(BABYLON.PushMaterial));
  43241. BABYLON.StandardMaterial = StandardMaterial;
  43242. })(BABYLON || (BABYLON = {}));
  43243. //# sourceMappingURL=babylon.standardMaterial.js.map
  43244. var BABYLON;
  43245. (function (BABYLON) {
  43246. /**
  43247. * Manages the defines for the PBR Material.
  43248. * @hiddenChildren
  43249. */
  43250. var PBRMaterialDefines = /** @class */ (function (_super) {
  43251. __extends(PBRMaterialDefines, _super);
  43252. /**
  43253. * Initializes the PBR Material defines.
  43254. */
  43255. function PBRMaterialDefines() {
  43256. var _this = _super.call(this) || this;
  43257. _this.PBR = true;
  43258. _this.MAINUV1 = false;
  43259. _this.MAINUV2 = false;
  43260. _this.UV1 = false;
  43261. _this.UV2 = false;
  43262. _this.ALBEDO = false;
  43263. _this.ALBEDODIRECTUV = 0;
  43264. _this.VERTEXCOLOR = false;
  43265. _this.AMBIENT = false;
  43266. _this.AMBIENTDIRECTUV = 0;
  43267. _this.AMBIENTINGRAYSCALE = false;
  43268. _this.OPACITY = false;
  43269. _this.VERTEXALPHA = false;
  43270. _this.OPACITYDIRECTUV = 0;
  43271. _this.OPACITYRGB = false;
  43272. _this.ALPHATEST = false;
  43273. _this.DEPTHPREPASS = false;
  43274. _this.ALPHABLEND = false;
  43275. _this.ALPHAFROMALBEDO = false;
  43276. _this.ALPHATESTVALUE = "0.5";
  43277. _this.SPECULAROVERALPHA = false;
  43278. _this.RADIANCEOVERALPHA = false;
  43279. _this.ALPHAFRESNEL = false;
  43280. _this.LINEARALPHAFRESNEL = false;
  43281. _this.PREMULTIPLYALPHA = false;
  43282. _this.EMISSIVE = false;
  43283. _this.EMISSIVEDIRECTUV = 0;
  43284. _this.REFLECTIVITY = false;
  43285. _this.REFLECTIVITYDIRECTUV = 0;
  43286. _this.SPECULARTERM = false;
  43287. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43288. _this.MICROSURFACEAUTOMATIC = false;
  43289. _this.LODBASEDMICROSFURACE = false;
  43290. _this.MICROSURFACEMAP = false;
  43291. _this.MICROSURFACEMAPDIRECTUV = 0;
  43292. _this.METALLICWORKFLOW = false;
  43293. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43294. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43295. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43296. _this.AOSTOREINMETALMAPRED = false;
  43297. _this.ENVIRONMENTBRDF = false;
  43298. _this.NORMAL = false;
  43299. _this.TANGENT = false;
  43300. _this.BUMP = false;
  43301. _this.BUMPDIRECTUV = 0;
  43302. _this.OBJECTSPACE_NORMALMAP = false;
  43303. _this.PARALLAX = false;
  43304. _this.PARALLAXOCCLUSION = false;
  43305. _this.NORMALXYSCALE = true;
  43306. _this.LIGHTMAP = false;
  43307. _this.LIGHTMAPDIRECTUV = 0;
  43308. _this.USELIGHTMAPASSHADOWMAP = false;
  43309. _this.GAMMALIGHTMAP = false;
  43310. _this.REFLECTION = false;
  43311. _this.REFLECTIONMAP_3D = false;
  43312. _this.REFLECTIONMAP_SPHERICAL = false;
  43313. _this.REFLECTIONMAP_PLANAR = false;
  43314. _this.REFLECTIONMAP_CUBIC = false;
  43315. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43316. _this.REFLECTIONMAP_PROJECTION = false;
  43317. _this.REFLECTIONMAP_SKYBOX = false;
  43318. _this.REFLECTIONMAP_EXPLICIT = false;
  43319. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43320. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43321. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43322. _this.INVERTCUBICMAP = false;
  43323. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43324. _this.USESPHERICALINVERTEX = false;
  43325. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43326. _this.LODINREFLECTIONALPHA = false;
  43327. _this.GAMMAREFLECTION = false;
  43328. _this.RGBDREFLECTION = false;
  43329. _this.RADIANCEOCCLUSION = false;
  43330. _this.HORIZONOCCLUSION = false;
  43331. _this.REFRACTION = false;
  43332. _this.REFRACTIONMAP_3D = false;
  43333. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43334. _this.LODINREFRACTIONALPHA = false;
  43335. _this.GAMMAREFRACTION = false;
  43336. _this.RGBDREFRACTION = false;
  43337. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43338. _this.INSTANCES = false;
  43339. _this.NUM_BONE_INFLUENCERS = 0;
  43340. _this.BonesPerMesh = 0;
  43341. _this.NONUNIFORMSCALING = false;
  43342. _this.MORPHTARGETS = false;
  43343. _this.MORPHTARGETS_NORMAL = false;
  43344. _this.MORPHTARGETS_TANGENT = false;
  43345. _this.NUM_MORPH_INFLUENCERS = 0;
  43346. _this.IMAGEPROCESSING = false;
  43347. _this.VIGNETTE = false;
  43348. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43349. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43350. _this.TONEMAPPING = false;
  43351. _this.CONTRAST = false;
  43352. _this.COLORCURVES = false;
  43353. _this.COLORGRADING = false;
  43354. _this.COLORGRADING3D = false;
  43355. _this.SAMPLER3DGREENDEPTH = false;
  43356. _this.SAMPLER3DBGRMAP = false;
  43357. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43358. _this.EXPOSURE = false;
  43359. _this.USEPHYSICALLIGHTFALLOFF = false;
  43360. _this.TWOSIDEDLIGHTING = false;
  43361. _this.SHADOWFLOAT = false;
  43362. _this.CLIPPLANE = false;
  43363. _this.POINTSIZE = false;
  43364. _this.FOG = false;
  43365. _this.LOGARITHMICDEPTH = false;
  43366. _this.FORCENORMALFORWARD = false;
  43367. _this.SPECULARAA = false;
  43368. _this.UNLIT = false;
  43369. _this.rebuild();
  43370. return _this;
  43371. }
  43372. /**
  43373. * Resets the PBR Material defines.
  43374. */
  43375. PBRMaterialDefines.prototype.reset = function () {
  43376. _super.prototype.reset.call(this);
  43377. this.ALPHATESTVALUE = "0.5";
  43378. this.PBR = true;
  43379. };
  43380. return PBRMaterialDefines;
  43381. }(BABYLON.MaterialDefines));
  43382. /**
  43383. * The Physically based material base class of BJS.
  43384. *
  43385. * This offers the main features of a standard PBR material.
  43386. * For more information, please refer to the documentation :
  43387. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43388. */
  43389. var PBRBaseMaterial = /** @class */ (function (_super) {
  43390. __extends(PBRBaseMaterial, _super);
  43391. /**
  43392. * Instantiates a new PBRMaterial instance.
  43393. *
  43394. * @param name The material name
  43395. * @param scene The scene the material will be use in.
  43396. */
  43397. function PBRBaseMaterial(name, scene) {
  43398. var _this = _super.call(this, name, scene) || this;
  43399. /**
  43400. * Intensity of the direct lights e.g. the four lights available in your scene.
  43401. * This impacts both the direct diffuse and specular highlights.
  43402. */
  43403. _this._directIntensity = 1.0;
  43404. /**
  43405. * Intensity of the emissive part of the material.
  43406. * This helps controlling the emissive effect without modifying the emissive color.
  43407. */
  43408. _this._emissiveIntensity = 1.0;
  43409. /**
  43410. * Intensity of the environment e.g. how much the environment will light the object
  43411. * either through harmonics for rough material or through the refelction for shiny ones.
  43412. */
  43413. _this._environmentIntensity = 1.0;
  43414. /**
  43415. * This is a special control allowing the reduction of the specular highlights coming from the
  43416. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43417. */
  43418. _this._specularIntensity = 1.0;
  43419. /**
  43420. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43421. */
  43422. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43423. /**
  43424. * Debug Control allowing disabling the bump map on this material.
  43425. */
  43426. _this._disableBumpMap = false;
  43427. /**
  43428. * AKA Occlusion Texture Intensity in other nomenclature.
  43429. */
  43430. _this._ambientTextureStrength = 1.0;
  43431. /**
  43432. * The color of a material in ambient lighting.
  43433. */
  43434. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43435. /**
  43436. * AKA Diffuse Color in other nomenclature.
  43437. */
  43438. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43439. /**
  43440. * AKA Specular Color in other nomenclature.
  43441. */
  43442. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43443. /**
  43444. * The color applied when light is reflected from a material.
  43445. */
  43446. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43447. /**
  43448. * The color applied when light is emitted from a material.
  43449. */
  43450. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43451. /**
  43452. * AKA Glossiness in other nomenclature.
  43453. */
  43454. _this._microSurface = 0.9;
  43455. /**
  43456. * source material index of refraction (IOR)' / 'destination material IOR.
  43457. */
  43458. _this._indexOfRefraction = 0.66;
  43459. /**
  43460. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43461. */
  43462. _this._invertRefractionY = false;
  43463. /**
  43464. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43465. * Materials half opaque for instance using refraction could benefit from this control.
  43466. */
  43467. _this._linkRefractionWithTransparency = false;
  43468. /**
  43469. * Specifies that the material will use the light map as a show map.
  43470. */
  43471. _this._useLightmapAsShadowmap = false;
  43472. /**
  43473. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43474. * makes the reflect vector face the model (under horizon).
  43475. */
  43476. _this._useHorizonOcclusion = true;
  43477. /**
  43478. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43479. * too much the area relying on ambient texture to define their ambient occlusion.
  43480. */
  43481. _this._useRadianceOcclusion = true;
  43482. /**
  43483. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43484. */
  43485. _this._useAlphaFromAlbedoTexture = false;
  43486. /**
  43487. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43488. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43489. */
  43490. _this._useSpecularOverAlpha = true;
  43491. /**
  43492. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43493. */
  43494. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43495. /**
  43496. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43497. */
  43498. _this._useRoughnessFromMetallicTextureAlpha = true;
  43499. /**
  43500. * Specifies if the metallic texture contains the roughness information in its green channel.
  43501. */
  43502. _this._useRoughnessFromMetallicTextureGreen = false;
  43503. /**
  43504. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43505. */
  43506. _this._useMetallnessFromMetallicTextureBlue = false;
  43507. /**
  43508. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43509. */
  43510. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43511. /**
  43512. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43513. */
  43514. _this._useAmbientInGrayScale = false;
  43515. /**
  43516. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43517. * The material will try to infer what glossiness each pixel should be.
  43518. */
  43519. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43520. /**
  43521. * BJS is using an harcoded light falloff based on a manually sets up range.
  43522. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43523. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43524. */
  43525. _this._usePhysicalLightFalloff = true;
  43526. /**
  43527. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43528. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43529. */
  43530. _this._useRadianceOverAlpha = true;
  43531. /**
  43532. * Allows using an object space normal map (instead of tangent space).
  43533. */
  43534. _this._useObjectSpaceNormalMap = false;
  43535. /**
  43536. * Allows using the bump map in parallax mode.
  43537. */
  43538. _this._useParallax = false;
  43539. /**
  43540. * Allows using the bump map in parallax occlusion mode.
  43541. */
  43542. _this._useParallaxOcclusion = false;
  43543. /**
  43544. * Controls the scale bias of the parallax mode.
  43545. */
  43546. _this._parallaxScaleBias = 0.05;
  43547. /**
  43548. * If sets to true, disables all the lights affecting the material.
  43549. */
  43550. _this._disableLighting = false;
  43551. /**
  43552. * Number of Simultaneous lights allowed on the material.
  43553. */
  43554. _this._maxSimultaneousLights = 4;
  43555. /**
  43556. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43557. */
  43558. _this._invertNormalMapX = false;
  43559. /**
  43560. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43561. */
  43562. _this._invertNormalMapY = false;
  43563. /**
  43564. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43565. */
  43566. _this._twoSidedLighting = false;
  43567. /**
  43568. * Defines the alpha limits in alpha test mode.
  43569. */
  43570. _this._alphaCutOff = 0.4;
  43571. /**
  43572. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43573. */
  43574. _this._forceAlphaTest = false;
  43575. /**
  43576. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43577. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43578. */
  43579. _this._useAlphaFresnel = false;
  43580. /**
  43581. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43582. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43583. */
  43584. _this._useLinearAlphaFresnel = false;
  43585. /**
  43586. * The transparency mode of the material.
  43587. */
  43588. _this._transparencyMode = null;
  43589. /**
  43590. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43591. * from cos thetav and roughness:
  43592. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43593. */
  43594. _this._environmentBRDFTexture = null;
  43595. /**
  43596. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43597. */
  43598. _this._forceIrradianceInFragment = false;
  43599. /**
  43600. * Force normal to face away from face.
  43601. */
  43602. _this._forceNormalForward = false;
  43603. /**
  43604. * Enables specular anti aliasing in the PBR shader.
  43605. * It will both interacts on the Geometry for analytical and IBL lighting.
  43606. * It also prefilter the roughness map based on the bump values.
  43607. */
  43608. _this._enableSpecularAntiAliasing = false;
  43609. /**
  43610. * Stores the available render targets.
  43611. */
  43612. _this._renderTargets = new BABYLON.SmartArray(16);
  43613. /**
  43614. * Sets the global ambient color for the material used in lighting calculations.
  43615. */
  43616. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43617. /**
  43618. * If set to true, no lighting calculations will be applied.
  43619. */
  43620. _this._unlit = false;
  43621. // Setup the default processing configuration to the scene.
  43622. _this._attachImageProcessingConfiguration(null);
  43623. _this.getRenderTargetTextures = function () {
  43624. _this._renderTargets.reset();
  43625. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43626. _this._renderTargets.push(_this._reflectionTexture);
  43627. }
  43628. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43629. _this._renderTargets.push(_this._refractionTexture);
  43630. }
  43631. return _this._renderTargets;
  43632. };
  43633. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43634. return _this;
  43635. }
  43636. /**
  43637. * Attaches a new image processing configuration to the PBR Material.
  43638. * @param configuration
  43639. */
  43640. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43641. var _this = this;
  43642. if (configuration === this._imageProcessingConfiguration) {
  43643. return;
  43644. }
  43645. // Detaches observer.
  43646. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43647. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43648. }
  43649. // Pick the scene configuration if needed.
  43650. if (!configuration) {
  43651. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43652. }
  43653. else {
  43654. this._imageProcessingConfiguration = configuration;
  43655. }
  43656. // Attaches observer.
  43657. if (this._imageProcessingConfiguration) {
  43658. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43659. _this._markAllSubMeshesAsImageProcessingDirty();
  43660. });
  43661. }
  43662. };
  43663. /**
  43664. * Gets the name of the material class.
  43665. */
  43666. PBRBaseMaterial.prototype.getClassName = function () {
  43667. return "PBRBaseMaterial";
  43668. };
  43669. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43670. /**
  43671. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43672. */
  43673. get: function () {
  43674. return this._useLogarithmicDepth;
  43675. },
  43676. /**
  43677. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43678. */
  43679. set: function (value) {
  43680. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43681. },
  43682. enumerable: true,
  43683. configurable: true
  43684. });
  43685. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43686. /**
  43687. * Gets the current transparency mode.
  43688. */
  43689. get: function () {
  43690. return this._transparencyMode;
  43691. },
  43692. /**
  43693. * Sets the transparency mode of the material.
  43694. *
  43695. * | Value | Type | Description |
  43696. * | ----- | ----------------------------------- | ----------- |
  43697. * | 0 | OPAQUE | |
  43698. * | 1 | ALPHATEST | |
  43699. * | 2 | ALPHABLEND | |
  43700. * | 3 | ALPHATESTANDBLEND | |
  43701. *
  43702. */
  43703. set: function (value) {
  43704. if (this._transparencyMode === value) {
  43705. return;
  43706. }
  43707. this._transparencyMode = value;
  43708. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43709. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43710. },
  43711. enumerable: true,
  43712. configurable: true
  43713. });
  43714. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43715. /**
  43716. * Returns true if alpha blending should be disabled.
  43717. */
  43718. get: function () {
  43719. return (this._linkRefractionWithTransparency ||
  43720. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43721. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43722. },
  43723. enumerable: true,
  43724. configurable: true
  43725. });
  43726. /**
  43727. * Specifies whether or not this material should be rendered in alpha blend mode.
  43728. */
  43729. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43730. if (this._disableAlphaBlending) {
  43731. return false;
  43732. }
  43733. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43734. };
  43735. /**
  43736. * Specifies if the mesh will require alpha blending.
  43737. * @param mesh - BJS mesh.
  43738. */
  43739. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43740. if (this._disableAlphaBlending) {
  43741. return false;
  43742. }
  43743. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43744. };
  43745. /**
  43746. * Specifies whether or not this material should be rendered in alpha test mode.
  43747. */
  43748. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43749. if (this._forceAlphaTest) {
  43750. return true;
  43751. }
  43752. if (this._linkRefractionWithTransparency) {
  43753. return false;
  43754. }
  43755. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43756. };
  43757. /**
  43758. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43759. */
  43760. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43761. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43762. };
  43763. /**
  43764. * Gets the texture used for the alpha test.
  43765. */
  43766. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43767. return this._albedoTexture;
  43768. };
  43769. /**
  43770. * Specifies that the submesh is ready to be used.
  43771. * @param mesh - BJS mesh.
  43772. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43773. * @param useInstances - Specifies that instances should be used.
  43774. * @returns - boolean indicating that the submesh is ready or not.
  43775. */
  43776. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43777. if (subMesh.effect && this.isFrozen) {
  43778. if (this._wasPreviouslyReady) {
  43779. return true;
  43780. }
  43781. }
  43782. if (!subMesh._materialDefines) {
  43783. subMesh._materialDefines = new PBRMaterialDefines();
  43784. }
  43785. var defines = subMesh._materialDefines;
  43786. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43787. if (defines._renderId === this.getScene().getRenderId()) {
  43788. return true;
  43789. }
  43790. }
  43791. var scene = this.getScene();
  43792. var engine = scene.getEngine();
  43793. if (defines._areTexturesDirty) {
  43794. if (scene.texturesEnabled) {
  43795. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43796. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43797. return false;
  43798. }
  43799. }
  43800. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43801. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43802. return false;
  43803. }
  43804. }
  43805. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43806. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43807. return false;
  43808. }
  43809. }
  43810. var reflectionTexture = this._getReflectionTexture();
  43811. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43812. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43813. return false;
  43814. }
  43815. }
  43816. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43817. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43818. return false;
  43819. }
  43820. }
  43821. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43822. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43823. return false;
  43824. }
  43825. }
  43826. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43827. if (this._metallicTexture) {
  43828. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43829. return false;
  43830. }
  43831. }
  43832. else if (this._reflectivityTexture) {
  43833. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43834. return false;
  43835. }
  43836. }
  43837. if (this._microSurfaceTexture) {
  43838. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43839. return false;
  43840. }
  43841. }
  43842. }
  43843. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43844. // Bump texture cannot be not blocking.
  43845. if (!this._bumpTexture.isReady()) {
  43846. return false;
  43847. }
  43848. }
  43849. var refractionTexture = this._getRefractionTexture();
  43850. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43851. if (!refractionTexture.isReadyOrNotBlocking()) {
  43852. return false;
  43853. }
  43854. }
  43855. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43856. // This is blocking.
  43857. if (!this._environmentBRDFTexture.isReady()) {
  43858. return false;
  43859. }
  43860. }
  43861. }
  43862. }
  43863. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43864. if (!this._imageProcessingConfiguration.isReady()) {
  43865. return false;
  43866. }
  43867. }
  43868. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43869. mesh.createNormals(true);
  43870. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43871. }
  43872. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43873. if (effect) {
  43874. scene.resetCachedMaterial();
  43875. subMesh.setEffect(effect, defines);
  43876. this.buildUniformLayout();
  43877. }
  43878. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43879. return false;
  43880. }
  43881. defines._renderId = scene.getRenderId();
  43882. this._wasPreviouslyReady = true;
  43883. return true;
  43884. };
  43885. /**
  43886. * Specifies if the material uses metallic roughness workflow.
  43887. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43888. */
  43889. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43890. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43891. return true;
  43892. }
  43893. return false;
  43894. };
  43895. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43896. if (onCompiled === void 0) { onCompiled = null; }
  43897. if (onError === void 0) { onError = null; }
  43898. if (useInstances === void 0) { useInstances = null; }
  43899. if (useClipPlane === void 0) { useClipPlane = null; }
  43900. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43901. if (!defines.isDirty) {
  43902. return null;
  43903. }
  43904. defines.markAsProcessed();
  43905. var scene = this.getScene();
  43906. var engine = scene.getEngine();
  43907. // Fallbacks
  43908. var fallbacks = new BABYLON.EffectFallbacks();
  43909. var fallbackRank = 0;
  43910. if (defines.USESPHERICALINVERTEX) {
  43911. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43912. }
  43913. if (defines.FOG) {
  43914. fallbacks.addFallback(fallbackRank, "FOG");
  43915. }
  43916. if (defines.SPECULARAA) {
  43917. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43918. }
  43919. if (defines.POINTSIZE) {
  43920. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43921. }
  43922. if (defines.LOGARITHMICDEPTH) {
  43923. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43924. }
  43925. if (defines.PARALLAX) {
  43926. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43927. }
  43928. if (defines.PARALLAXOCCLUSION) {
  43929. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43930. }
  43931. if (defines.ENVIRONMENTBRDF) {
  43932. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43933. }
  43934. if (defines.TANGENT) {
  43935. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43936. }
  43937. if (defines.BUMP) {
  43938. fallbacks.addFallback(fallbackRank++, "BUMP");
  43939. }
  43940. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  43941. if (defines.SPECULARTERM) {
  43942. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  43943. }
  43944. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  43945. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  43946. }
  43947. if (defines.LIGHTMAP) {
  43948. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  43949. }
  43950. if (defines.NORMAL) {
  43951. fallbacks.addFallback(fallbackRank++, "NORMAL");
  43952. }
  43953. if (defines.AMBIENT) {
  43954. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  43955. }
  43956. if (defines.EMISSIVE) {
  43957. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  43958. }
  43959. if (defines.VERTEXCOLOR) {
  43960. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  43961. }
  43962. if (defines.NUM_BONE_INFLUENCERS > 0) {
  43963. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  43964. }
  43965. if (defines.MORPHTARGETS) {
  43966. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  43967. }
  43968. //Attributes
  43969. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43970. if (defines.NORMAL) {
  43971. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43972. }
  43973. if (defines.TANGENT) {
  43974. attribs.push(BABYLON.VertexBuffer.TangentKind);
  43975. }
  43976. if (defines.UV1) {
  43977. attribs.push(BABYLON.VertexBuffer.UVKind);
  43978. }
  43979. if (defines.UV2) {
  43980. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43981. }
  43982. if (defines.VERTEXCOLOR) {
  43983. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43984. }
  43985. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43986. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43987. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43988. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  43989. "vFogInfos", "vFogColor", "pointSize",
  43990. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  43991. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43992. "mBones",
  43993. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  43994. "vLightingIntensity",
  43995. "logarithmicDepthConstant",
  43996. "vSphericalX", "vSphericalY", "vSphericalZ",
  43997. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  43998. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  43999. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44000. "vTangentSpaceParams"
  44001. ];
  44002. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44003. "bumpSampler", "lightmapSampler", "opacitySampler",
  44004. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44005. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44006. "microSurfaceSampler", "environmentBrdfSampler"];
  44007. var uniformBuffers = ["Material", "Scene"];
  44008. if (BABYLON.ImageProcessingConfiguration) {
  44009. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44010. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44011. }
  44012. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44013. uniformsNames: uniforms,
  44014. uniformBuffersNames: uniformBuffers,
  44015. samplers: samplers,
  44016. defines: defines,
  44017. maxSimultaneousLights: this._maxSimultaneousLights
  44018. });
  44019. var join = defines.toString();
  44020. return engine.createEffect("pbr", {
  44021. attributes: attribs,
  44022. uniformsNames: uniforms,
  44023. uniformBuffersNames: uniformBuffers,
  44024. samplers: samplers,
  44025. defines: join,
  44026. fallbacks: fallbacks,
  44027. onCompiled: onCompiled,
  44028. onError: onError,
  44029. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44030. }, engine);
  44031. };
  44032. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44033. if (useInstances === void 0) { useInstances = null; }
  44034. if (useClipPlane === void 0) { useClipPlane = null; }
  44035. var scene = this.getScene();
  44036. var engine = scene.getEngine();
  44037. // Lights
  44038. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44039. defines._needNormals = true;
  44040. // Textures
  44041. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44042. if (defines._areTexturesDirty) {
  44043. defines._needUVs = false;
  44044. if (scene.texturesEnabled) {
  44045. if (scene.getEngine().getCaps().textureLOD) {
  44046. defines.LODBASEDMICROSFURACE = true;
  44047. }
  44048. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44049. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44050. }
  44051. else {
  44052. defines.ALBEDO = false;
  44053. }
  44054. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44055. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44056. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44057. }
  44058. else {
  44059. defines.AMBIENT = false;
  44060. }
  44061. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44062. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44063. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44064. }
  44065. else {
  44066. defines.OPACITY = false;
  44067. }
  44068. var reflectionTexture = this._getReflectionTexture();
  44069. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44070. defines.REFLECTION = true;
  44071. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44072. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44073. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44074. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44075. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44076. defines.INVERTCUBICMAP = true;
  44077. }
  44078. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44079. switch (reflectionTexture.coordinatesMode) {
  44080. case BABYLON.Texture.EXPLICIT_MODE:
  44081. defines.REFLECTIONMAP_EXPLICIT = true;
  44082. break;
  44083. case BABYLON.Texture.PLANAR_MODE:
  44084. defines.REFLECTIONMAP_PLANAR = true;
  44085. break;
  44086. case BABYLON.Texture.PROJECTION_MODE:
  44087. defines.REFLECTIONMAP_PROJECTION = true;
  44088. break;
  44089. case BABYLON.Texture.SKYBOX_MODE:
  44090. defines.REFLECTIONMAP_SKYBOX = true;
  44091. break;
  44092. case BABYLON.Texture.SPHERICAL_MODE:
  44093. defines.REFLECTIONMAP_SPHERICAL = true;
  44094. break;
  44095. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44096. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44097. break;
  44098. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44099. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44100. break;
  44101. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44102. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44103. break;
  44104. case BABYLON.Texture.CUBIC_MODE:
  44105. case BABYLON.Texture.INVCUBIC_MODE:
  44106. default:
  44107. defines.REFLECTIONMAP_CUBIC = true;
  44108. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44109. break;
  44110. }
  44111. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44112. if (reflectionTexture.sphericalPolynomial) {
  44113. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44114. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44115. defines.USESPHERICALINVERTEX = false;
  44116. }
  44117. else {
  44118. defines.USESPHERICALINVERTEX = true;
  44119. }
  44120. }
  44121. }
  44122. }
  44123. else {
  44124. defines.REFLECTION = false;
  44125. defines.REFLECTIONMAP_3D = false;
  44126. defines.REFLECTIONMAP_SPHERICAL = false;
  44127. defines.REFLECTIONMAP_PLANAR = false;
  44128. defines.REFLECTIONMAP_CUBIC = false;
  44129. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44130. defines.REFLECTIONMAP_PROJECTION = false;
  44131. defines.REFLECTIONMAP_SKYBOX = false;
  44132. defines.REFLECTIONMAP_EXPLICIT = false;
  44133. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44134. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44135. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44136. defines.INVERTCUBICMAP = false;
  44137. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44138. defines.USESPHERICALINVERTEX = false;
  44139. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44140. defines.LODINREFLECTIONALPHA = false;
  44141. defines.GAMMAREFLECTION = false;
  44142. defines.RGBDREFLECTION = false;
  44143. }
  44144. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44145. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44146. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44147. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44148. }
  44149. else {
  44150. defines.LIGHTMAP = false;
  44151. }
  44152. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44153. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44154. }
  44155. else {
  44156. defines.EMISSIVE = false;
  44157. }
  44158. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44159. if (this._metallicTexture) {
  44160. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44161. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44162. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44163. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44164. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44165. }
  44166. else if (this._reflectivityTexture) {
  44167. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44168. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44169. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44170. }
  44171. else {
  44172. defines.REFLECTIVITY = false;
  44173. }
  44174. if (this._microSurfaceTexture) {
  44175. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44176. }
  44177. else {
  44178. defines.MICROSURFACEMAP = false;
  44179. }
  44180. }
  44181. else {
  44182. defines.REFLECTIVITY = false;
  44183. defines.MICROSURFACEMAP = false;
  44184. }
  44185. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44186. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44187. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44188. defines.PARALLAX = true;
  44189. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44190. }
  44191. else {
  44192. defines.PARALLAX = false;
  44193. }
  44194. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44195. }
  44196. else {
  44197. defines.BUMP = false;
  44198. }
  44199. var refractionTexture = this._getRefractionTexture();
  44200. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44201. defines.REFRACTION = true;
  44202. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44203. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44204. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44205. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44206. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44207. if (this._linkRefractionWithTransparency) {
  44208. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44209. }
  44210. }
  44211. else {
  44212. defines.REFRACTION = false;
  44213. }
  44214. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44215. defines.ENVIRONMENTBRDF = true;
  44216. }
  44217. else {
  44218. defines.ENVIRONMENTBRDF = false;
  44219. }
  44220. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44221. defines.ALPHAFROMALBEDO = true;
  44222. }
  44223. else {
  44224. defines.ALPHAFROMALBEDO = false;
  44225. }
  44226. }
  44227. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44228. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44229. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44230. if (!this.backFaceCulling && this._twoSidedLighting) {
  44231. defines.TWOSIDEDLIGHTING = true;
  44232. }
  44233. else {
  44234. defines.TWOSIDEDLIGHTING = false;
  44235. }
  44236. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44237. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44238. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44239. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44240. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44241. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44242. }
  44243. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44244. this._imageProcessingConfiguration.prepareDefines(defines);
  44245. }
  44246. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44247. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44248. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44249. // Misc.
  44250. if (defines._areMiscDirty) {
  44251. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44252. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44253. }
  44254. // Values that need to be evaluated on every frame
  44255. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44256. // Attribs
  44257. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44258. };
  44259. /**
  44260. * Force shader compilation
  44261. */
  44262. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44263. var _this = this;
  44264. var localOptions = __assign({ clipPlane: false }, options);
  44265. var defines = new PBRMaterialDefines();
  44266. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44267. if (effect.isReady()) {
  44268. if (onCompiled) {
  44269. onCompiled(this);
  44270. }
  44271. }
  44272. else {
  44273. effect.onCompileObservable.add(function () {
  44274. if (onCompiled) {
  44275. onCompiled(_this);
  44276. }
  44277. });
  44278. }
  44279. };
  44280. /**
  44281. * Initializes the uniform buffer layout for the shader.
  44282. */
  44283. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44284. // Order is important !
  44285. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44286. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44287. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44288. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44289. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44290. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44291. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44292. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44293. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44294. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44295. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44296. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44297. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44298. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44299. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44300. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44301. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44302. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44303. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44304. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44305. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44306. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44307. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44308. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44309. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44310. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44311. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44312. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44313. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44314. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44315. this._uniformBuffer.addUniform("pointSize", 1);
  44316. this._uniformBuffer.create();
  44317. };
  44318. /**
  44319. * Unbinds the textures.
  44320. */
  44321. PBRBaseMaterial.prototype.unbind = function () {
  44322. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44323. this._uniformBuffer.setTexture("reflectionSampler", null);
  44324. }
  44325. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44326. this._uniformBuffer.setTexture("refractionSampler", null);
  44327. }
  44328. _super.prototype.unbind.call(this);
  44329. };
  44330. /**
  44331. * Binds the submesh data.
  44332. * @param world - The world matrix.
  44333. * @param mesh - The BJS mesh.
  44334. * @param subMesh - A submesh of the BJS mesh.
  44335. */
  44336. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44337. var scene = this.getScene();
  44338. var defines = subMesh._materialDefines;
  44339. if (!defines) {
  44340. return;
  44341. }
  44342. var effect = subMesh.effect;
  44343. if (!effect) {
  44344. return;
  44345. }
  44346. this._activeEffect = effect;
  44347. // Matrices
  44348. this.bindOnlyWorldMatrix(world);
  44349. // Normal Matrix
  44350. if (defines.OBJECTSPACE_NORMALMAP) {
  44351. world.toNormalMatrix(this._normalMatrix);
  44352. this.bindOnlyNormalMatrix(this._normalMatrix);
  44353. }
  44354. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44355. // Bones
  44356. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44357. var reflectionTexture = null;
  44358. if (mustRebind) {
  44359. this._uniformBuffer.bindToEffect(effect, "Material");
  44360. this.bindViewProjection(effect);
  44361. reflectionTexture = this._getReflectionTexture();
  44362. var refractionTexture = this._getRefractionTexture();
  44363. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44364. // Texture uniforms
  44365. if (scene.texturesEnabled) {
  44366. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44367. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44368. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44369. }
  44370. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44371. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44372. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44373. }
  44374. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44375. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44376. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44377. }
  44378. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44379. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44380. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44381. if (reflectionTexture.boundingBoxSize) {
  44382. var cubeTexture = reflectionTexture;
  44383. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44384. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44385. }
  44386. var polynomials = reflectionTexture.sphericalPolynomial;
  44387. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44388. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44389. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44390. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44391. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44392. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44393. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44394. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44395. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44396. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44397. }
  44398. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44399. }
  44400. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44401. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44402. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44403. }
  44404. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44405. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44406. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44407. }
  44408. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44409. if (this._metallicTexture) {
  44410. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44411. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44412. }
  44413. else if (this._reflectivityTexture) {
  44414. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44415. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44416. }
  44417. if (this._microSurfaceTexture) {
  44418. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44419. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44420. }
  44421. }
  44422. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44423. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44424. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44425. if (scene._mirroredCameraPosition) {
  44426. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44427. }
  44428. else {
  44429. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44430. }
  44431. }
  44432. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44433. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44434. var depth = 1.0;
  44435. if (!refractionTexture.isCube) {
  44436. if (refractionTexture.depth) {
  44437. depth = refractionTexture.depth;
  44438. }
  44439. }
  44440. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44441. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44442. }
  44443. }
  44444. // Point size
  44445. if (this.pointsCloud) {
  44446. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44447. }
  44448. // Colors
  44449. if (defines.METALLICWORKFLOW) {
  44450. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44451. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44452. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44453. }
  44454. else {
  44455. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44456. }
  44457. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44458. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44459. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44460. // Misc
  44461. this._lightingInfos.x = this._directIntensity;
  44462. this._lightingInfos.y = this._emissiveIntensity;
  44463. this._lightingInfos.z = this._environmentIntensity;
  44464. this._lightingInfos.w = this._specularIntensity;
  44465. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44466. }
  44467. // Textures
  44468. if (scene.texturesEnabled) {
  44469. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44470. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44471. }
  44472. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44473. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44474. }
  44475. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44476. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44477. }
  44478. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44479. if (defines.LODBASEDMICROSFURACE) {
  44480. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44481. }
  44482. else {
  44483. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44484. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44485. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44486. }
  44487. }
  44488. if (defines.ENVIRONMENTBRDF) {
  44489. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44490. }
  44491. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44492. if (defines.LODBASEDMICROSFURACE) {
  44493. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44494. }
  44495. else {
  44496. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44497. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44498. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44499. }
  44500. }
  44501. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44502. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44503. }
  44504. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44505. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44506. }
  44507. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44508. if (this._metallicTexture) {
  44509. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44510. }
  44511. else if (this._reflectivityTexture) {
  44512. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44513. }
  44514. if (this._microSurfaceTexture) {
  44515. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44516. }
  44517. }
  44518. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44519. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44520. }
  44521. }
  44522. // Clip plane
  44523. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44524. // Colors
  44525. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44526. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44527. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44528. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44529. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44530. }
  44531. if (mustRebind || !this.isFrozen) {
  44532. // Lights
  44533. if (scene.lightsEnabled && !this._disableLighting) {
  44534. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44535. }
  44536. // View
  44537. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44538. this.bindView(effect);
  44539. }
  44540. // Fog
  44541. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44542. // Morph targets
  44543. if (defines.NUM_MORPH_INFLUENCERS) {
  44544. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44545. }
  44546. // image processing
  44547. this._imageProcessingConfiguration.bind(this._activeEffect);
  44548. // Log. depth
  44549. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44550. }
  44551. this._uniformBuffer.update();
  44552. this._afterBind(mesh, this._activeEffect);
  44553. };
  44554. /**
  44555. * Returns the animatable textures.
  44556. * @returns - Array of animatable textures.
  44557. */
  44558. PBRBaseMaterial.prototype.getAnimatables = function () {
  44559. var results = [];
  44560. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44561. results.push(this._albedoTexture);
  44562. }
  44563. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44564. results.push(this._ambientTexture);
  44565. }
  44566. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44567. results.push(this._opacityTexture);
  44568. }
  44569. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44570. results.push(this._reflectionTexture);
  44571. }
  44572. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44573. results.push(this._emissiveTexture);
  44574. }
  44575. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44576. results.push(this._metallicTexture);
  44577. }
  44578. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44579. results.push(this._reflectivityTexture);
  44580. }
  44581. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44582. results.push(this._bumpTexture);
  44583. }
  44584. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44585. results.push(this._lightmapTexture);
  44586. }
  44587. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44588. results.push(this._refractionTexture);
  44589. }
  44590. return results;
  44591. };
  44592. /**
  44593. * Returns the texture used for reflections.
  44594. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44595. */
  44596. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44597. if (this._reflectionTexture) {
  44598. return this._reflectionTexture;
  44599. }
  44600. return this.getScene().environmentTexture;
  44601. };
  44602. /**
  44603. * Returns the texture used for refraction or null if none is used.
  44604. * @returns - Refection texture if present. If no refraction texture and refraction
  44605. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44606. */
  44607. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44608. if (this._refractionTexture) {
  44609. return this._refractionTexture;
  44610. }
  44611. if (this._linkRefractionWithTransparency) {
  44612. return this.getScene().environmentTexture;
  44613. }
  44614. return null;
  44615. };
  44616. /**
  44617. * Disposes the resources of the material.
  44618. * @param forceDisposeEffect - Forces the disposal of effects.
  44619. * @param forceDisposeTextures - Forces the disposal of all textures.
  44620. */
  44621. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44622. if (forceDisposeTextures) {
  44623. if (this._albedoTexture) {
  44624. this._albedoTexture.dispose();
  44625. }
  44626. if (this._ambientTexture) {
  44627. this._ambientTexture.dispose();
  44628. }
  44629. if (this._opacityTexture) {
  44630. this._opacityTexture.dispose();
  44631. }
  44632. if (this._reflectionTexture) {
  44633. this._reflectionTexture.dispose();
  44634. }
  44635. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44636. this._environmentBRDFTexture.dispose();
  44637. }
  44638. if (this._emissiveTexture) {
  44639. this._emissiveTexture.dispose();
  44640. }
  44641. if (this._metallicTexture) {
  44642. this._metallicTexture.dispose();
  44643. }
  44644. if (this._reflectivityTexture) {
  44645. this._reflectivityTexture.dispose();
  44646. }
  44647. if (this._bumpTexture) {
  44648. this._bumpTexture.dispose();
  44649. }
  44650. if (this._lightmapTexture) {
  44651. this._lightmapTexture.dispose();
  44652. }
  44653. if (this._refractionTexture) {
  44654. this._refractionTexture.dispose();
  44655. }
  44656. }
  44657. this._renderTargets.dispose();
  44658. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44659. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44660. }
  44661. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44662. };
  44663. /**
  44664. * Stores the reflectivity values based on metallic roughness workflow.
  44665. */
  44666. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44667. __decorate([
  44668. BABYLON.serializeAsImageProcessingConfiguration()
  44669. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44670. __decorate([
  44671. BABYLON.serialize()
  44672. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44673. __decorate([
  44674. BABYLON.serialize()
  44675. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44676. return PBRBaseMaterial;
  44677. }(BABYLON.PushMaterial));
  44678. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44679. })(BABYLON || (BABYLON = {}));
  44680. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44681. var BABYLON;
  44682. (function (BABYLON) {
  44683. /**
  44684. * The Physically based simple base material of BJS.
  44685. *
  44686. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44687. * It is used as the base class for both the specGloss and metalRough conventions.
  44688. */
  44689. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44690. __extends(PBRBaseSimpleMaterial, _super);
  44691. /**
  44692. * Instantiates a new PBRMaterial instance.
  44693. *
  44694. * @param name The material name
  44695. * @param scene The scene the material will be use in.
  44696. */
  44697. function PBRBaseSimpleMaterial(name, scene) {
  44698. var _this = _super.call(this, name, scene) || this;
  44699. /**
  44700. * Number of Simultaneous lights allowed on the material.
  44701. */
  44702. _this.maxSimultaneousLights = 4;
  44703. /**
  44704. * If sets to true, disables all the lights affecting the material.
  44705. */
  44706. _this.disableLighting = false;
  44707. /**
  44708. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44709. */
  44710. _this.invertNormalMapX = false;
  44711. /**
  44712. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44713. */
  44714. _this.invertNormalMapY = false;
  44715. /**
  44716. * Emissivie color used to self-illuminate the model.
  44717. */
  44718. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44719. /**
  44720. * Occlusion Channel Strenght.
  44721. */
  44722. _this.occlusionStrength = 1.0;
  44723. _this.useLightmapAsShadowmap = false;
  44724. _this._useAlphaFromAlbedoTexture = true;
  44725. _this._useAmbientInGrayScale = true;
  44726. return _this;
  44727. }
  44728. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44729. /**
  44730. * Gets the current double sided mode.
  44731. */
  44732. get: function () {
  44733. return this._twoSidedLighting;
  44734. },
  44735. /**
  44736. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44737. */
  44738. set: function (value) {
  44739. if (this._twoSidedLighting === value) {
  44740. return;
  44741. }
  44742. this._twoSidedLighting = value;
  44743. this.backFaceCulling = !value;
  44744. this._markAllSubMeshesAsTexturesDirty();
  44745. },
  44746. enumerable: true,
  44747. configurable: true
  44748. });
  44749. /**
  44750. * Return the active textures of the material.
  44751. */
  44752. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44753. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44754. if (this.environmentTexture) {
  44755. activeTextures.push(this.environmentTexture);
  44756. }
  44757. if (this.normalTexture) {
  44758. activeTextures.push(this.normalTexture);
  44759. }
  44760. if (this.emissiveTexture) {
  44761. activeTextures.push(this.emissiveTexture);
  44762. }
  44763. if (this.occlusionTexture) {
  44764. activeTextures.push(this.occlusionTexture);
  44765. }
  44766. if (this.lightmapTexture) {
  44767. activeTextures.push(this.lightmapTexture);
  44768. }
  44769. return activeTextures;
  44770. };
  44771. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44772. if (_super.prototype.hasTexture.call(this, texture)) {
  44773. return true;
  44774. }
  44775. if (this.lightmapTexture === texture) {
  44776. return true;
  44777. }
  44778. return false;
  44779. };
  44780. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44781. return "PBRBaseSimpleMaterial";
  44782. };
  44783. __decorate([
  44784. BABYLON.serialize(),
  44785. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44786. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44787. __decorate([
  44788. BABYLON.serialize(),
  44789. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44790. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44791. __decorate([
  44792. BABYLON.serializeAsTexture(),
  44793. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44794. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44795. __decorate([
  44796. BABYLON.serialize(),
  44797. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44798. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44799. __decorate([
  44800. BABYLON.serialize(),
  44801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44802. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44803. __decorate([
  44804. BABYLON.serializeAsTexture(),
  44805. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44806. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44807. __decorate([
  44808. BABYLON.serializeAsColor3("emissive"),
  44809. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44810. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44811. __decorate([
  44812. BABYLON.serializeAsTexture(),
  44813. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44814. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44815. __decorate([
  44816. BABYLON.serialize(),
  44817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44818. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44819. __decorate([
  44820. BABYLON.serializeAsTexture(),
  44821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44822. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44823. __decorate([
  44824. BABYLON.serialize(),
  44825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44826. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44827. __decorate([
  44828. BABYLON.serialize()
  44829. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44830. __decorate([
  44831. BABYLON.serializeAsTexture(),
  44832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44833. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44834. __decorate([
  44835. BABYLON.serialize(),
  44836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44837. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44838. return PBRBaseSimpleMaterial;
  44839. }(BABYLON.PBRBaseMaterial));
  44840. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44841. })(BABYLON || (BABYLON = {}));
  44842. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44843. var BABYLON;
  44844. (function (BABYLON) {
  44845. /**
  44846. * The Physically based material of BJS.
  44847. *
  44848. * This offers the main features of a standard PBR material.
  44849. * For more information, please refer to the documentation :
  44850. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44851. */
  44852. var PBRMaterial = /** @class */ (function (_super) {
  44853. __extends(PBRMaterial, _super);
  44854. /**
  44855. * Instantiates a new PBRMaterial instance.
  44856. *
  44857. * @param name The material name
  44858. * @param scene The scene the material will be use in.
  44859. */
  44860. function PBRMaterial(name, scene) {
  44861. var _this = _super.call(this, name, scene) || this;
  44862. /**
  44863. * Intensity of the direct lights e.g. the four lights available in your scene.
  44864. * This impacts both the direct diffuse and specular highlights.
  44865. */
  44866. _this.directIntensity = 1.0;
  44867. /**
  44868. * Intensity of the emissive part of the material.
  44869. * This helps controlling the emissive effect without modifying the emissive color.
  44870. */
  44871. _this.emissiveIntensity = 1.0;
  44872. /**
  44873. * Intensity of the environment e.g. how much the environment will light the object
  44874. * either through harmonics for rough material or through the refelction for shiny ones.
  44875. */
  44876. _this.environmentIntensity = 1.0;
  44877. /**
  44878. * This is a special control allowing the reduction of the specular highlights coming from the
  44879. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44880. */
  44881. _this.specularIntensity = 1.0;
  44882. /**
  44883. * Debug Control allowing disabling the bump map on this material.
  44884. */
  44885. _this.disableBumpMap = false;
  44886. /**
  44887. * AKA Occlusion Texture Intensity in other nomenclature.
  44888. */
  44889. _this.ambientTextureStrength = 1.0;
  44890. /**
  44891. * The color of a material in ambient lighting.
  44892. */
  44893. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44894. /**
  44895. * AKA Diffuse Color in other nomenclature.
  44896. */
  44897. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44898. /**
  44899. * AKA Specular Color in other nomenclature.
  44900. */
  44901. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44902. /**
  44903. * The color reflected from the material.
  44904. */
  44905. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44906. /**
  44907. * The color emitted from the material.
  44908. */
  44909. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44910. /**
  44911. * AKA Glossiness in other nomenclature.
  44912. */
  44913. _this.microSurface = 1.0;
  44914. /**
  44915. * source material index of refraction (IOR)' / 'destination material IOR.
  44916. */
  44917. _this.indexOfRefraction = 0.66;
  44918. /**
  44919. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44920. */
  44921. _this.invertRefractionY = false;
  44922. /**
  44923. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44924. * Materials half opaque for instance using refraction could benefit from this control.
  44925. */
  44926. _this.linkRefractionWithTransparency = false;
  44927. _this.useLightmapAsShadowmap = false;
  44928. /**
  44929. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44930. */
  44931. _this.useAlphaFromAlbedoTexture = false;
  44932. /**
  44933. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44934. */
  44935. _this.forceAlphaTest = false;
  44936. /**
  44937. * Defines the alpha limits in alpha test mode.
  44938. */
  44939. _this.alphaCutOff = 0.4;
  44940. /**
  44941. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44942. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44943. */
  44944. _this.useSpecularOverAlpha = true;
  44945. /**
  44946. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44947. */
  44948. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44949. /**
  44950. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44951. */
  44952. _this.useRoughnessFromMetallicTextureAlpha = true;
  44953. /**
  44954. * Specifies if the metallic texture contains the roughness information in its green channel.
  44955. */
  44956. _this.useRoughnessFromMetallicTextureGreen = false;
  44957. /**
  44958. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44959. */
  44960. _this.useMetallnessFromMetallicTextureBlue = false;
  44961. /**
  44962. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44963. */
  44964. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  44965. /**
  44966. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44967. */
  44968. _this.useAmbientInGrayScale = false;
  44969. /**
  44970. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44971. * The material will try to infer what glossiness each pixel should be.
  44972. */
  44973. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  44974. /**
  44975. * BJS is using an harcoded light falloff based on a manually sets up range.
  44976. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44977. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44978. */
  44979. _this.usePhysicalLightFalloff = true;
  44980. /**
  44981. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44982. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44983. */
  44984. _this.useRadianceOverAlpha = true;
  44985. /**
  44986. * Allows using an object space normal map (instead of tangent space).
  44987. */
  44988. _this.useObjectSpaceNormalMap = false;
  44989. /**
  44990. * Allows using the bump map in parallax mode.
  44991. */
  44992. _this.useParallax = false;
  44993. /**
  44994. * Allows using the bump map in parallax occlusion mode.
  44995. */
  44996. _this.useParallaxOcclusion = false;
  44997. /**
  44998. * Controls the scale bias of the parallax mode.
  44999. */
  45000. _this.parallaxScaleBias = 0.05;
  45001. /**
  45002. * If sets to true, disables all the lights affecting the material.
  45003. */
  45004. _this.disableLighting = false;
  45005. /**
  45006. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45007. */
  45008. _this.forceIrradianceInFragment = false;
  45009. /**
  45010. * Number of Simultaneous lights allowed on the material.
  45011. */
  45012. _this.maxSimultaneousLights = 4;
  45013. /**
  45014. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45015. */
  45016. _this.invertNormalMapX = false;
  45017. /**
  45018. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45019. */
  45020. _this.invertNormalMapY = false;
  45021. /**
  45022. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45023. */
  45024. _this.twoSidedLighting = false;
  45025. /**
  45026. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45027. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45028. */
  45029. _this.useAlphaFresnel = false;
  45030. /**
  45031. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45032. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45033. */
  45034. _this.useLinearAlphaFresnel = false;
  45035. /**
  45036. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45037. * And/Or occlude the blended part.
  45038. */
  45039. _this.environmentBRDFTexture = null;
  45040. /**
  45041. * Force normal to face away from face.
  45042. */
  45043. _this.forceNormalForward = false;
  45044. /**
  45045. * Enables specular anti aliasing in the PBR shader.
  45046. * It will both interacts on the Geometry for analytical and IBL lighting.
  45047. * It also prefilter the roughness map based on the bump values.
  45048. */
  45049. _this.enableSpecularAntiAliasing = false;
  45050. /**
  45051. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45052. * makes the reflect vector face the model (under horizon).
  45053. */
  45054. _this.useHorizonOcclusion = true;
  45055. /**
  45056. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45057. * too much the area relying on ambient texture to define their ambient occlusion.
  45058. */
  45059. _this.useRadianceOcclusion = true;
  45060. /**
  45061. * If set to true, no lighting calculations will be applied.
  45062. */
  45063. _this.unlit = false;
  45064. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45065. return _this;
  45066. }
  45067. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45068. /**
  45069. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45070. */
  45071. get: function () {
  45072. return this._PBRMATERIAL_OPAQUE;
  45073. },
  45074. enumerable: true,
  45075. configurable: true
  45076. });
  45077. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45078. /**
  45079. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45080. */
  45081. get: function () {
  45082. return this._PBRMATERIAL_ALPHATEST;
  45083. },
  45084. enumerable: true,
  45085. configurable: true
  45086. });
  45087. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45088. /**
  45089. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45090. */
  45091. get: function () {
  45092. return this._PBRMATERIAL_ALPHABLEND;
  45093. },
  45094. enumerable: true,
  45095. configurable: true
  45096. });
  45097. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45098. /**
  45099. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45100. * They are also discarded below the alpha cutoff threshold to improve performances.
  45101. */
  45102. get: function () {
  45103. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45104. },
  45105. enumerable: true,
  45106. configurable: true
  45107. });
  45108. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45109. /**
  45110. * Gets the image processing configuration used either in this material.
  45111. */
  45112. get: function () {
  45113. return this._imageProcessingConfiguration;
  45114. },
  45115. /**
  45116. * Sets the Default image processing configuration used either in the this material.
  45117. *
  45118. * If sets to null, the scene one is in use.
  45119. */
  45120. set: function (value) {
  45121. this._attachImageProcessingConfiguration(value);
  45122. // Ensure the effect will be rebuilt.
  45123. this._markAllSubMeshesAsTexturesDirty();
  45124. },
  45125. enumerable: true,
  45126. configurable: true
  45127. });
  45128. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45129. /**
  45130. * Gets wether the color curves effect is enabled.
  45131. */
  45132. get: function () {
  45133. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45134. },
  45135. /**
  45136. * Sets wether the color curves effect is enabled.
  45137. */
  45138. set: function (value) {
  45139. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45140. },
  45141. enumerable: true,
  45142. configurable: true
  45143. });
  45144. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45145. /**
  45146. * Gets wether the color grading effect is enabled.
  45147. */
  45148. get: function () {
  45149. return this.imageProcessingConfiguration.colorGradingEnabled;
  45150. },
  45151. /**
  45152. * Gets wether the color grading effect is enabled.
  45153. */
  45154. set: function (value) {
  45155. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45156. },
  45157. enumerable: true,
  45158. configurable: true
  45159. });
  45160. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45161. /**
  45162. * Gets wether tonemapping is enabled or not.
  45163. */
  45164. get: function () {
  45165. return this._imageProcessingConfiguration.toneMappingEnabled;
  45166. },
  45167. /**
  45168. * Sets wether tonemapping is enabled or not
  45169. */
  45170. set: function (value) {
  45171. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45172. },
  45173. enumerable: true,
  45174. configurable: true
  45175. });
  45176. ;
  45177. ;
  45178. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45179. /**
  45180. * The camera exposure used on this material.
  45181. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45182. * This corresponds to a photographic exposure.
  45183. */
  45184. get: function () {
  45185. return this._imageProcessingConfiguration.exposure;
  45186. },
  45187. /**
  45188. * The camera exposure used on this material.
  45189. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45190. * This corresponds to a photographic exposure.
  45191. */
  45192. set: function (value) {
  45193. this._imageProcessingConfiguration.exposure = value;
  45194. },
  45195. enumerable: true,
  45196. configurable: true
  45197. });
  45198. ;
  45199. ;
  45200. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45201. /**
  45202. * Gets The camera contrast used on this material.
  45203. */
  45204. get: function () {
  45205. return this._imageProcessingConfiguration.contrast;
  45206. },
  45207. /**
  45208. * Sets The camera contrast used on this material.
  45209. */
  45210. set: function (value) {
  45211. this._imageProcessingConfiguration.contrast = value;
  45212. },
  45213. enumerable: true,
  45214. configurable: true
  45215. });
  45216. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45217. /**
  45218. * Gets the Color Grading 2D Lookup Texture.
  45219. */
  45220. get: function () {
  45221. return this._imageProcessingConfiguration.colorGradingTexture;
  45222. },
  45223. /**
  45224. * Sets the Color Grading 2D Lookup Texture.
  45225. */
  45226. set: function (value) {
  45227. this._imageProcessingConfiguration.colorGradingTexture = value;
  45228. },
  45229. enumerable: true,
  45230. configurable: true
  45231. });
  45232. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45233. /**
  45234. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45235. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45236. * 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;
  45237. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45238. */
  45239. get: function () {
  45240. return this._imageProcessingConfiguration.colorCurves;
  45241. },
  45242. /**
  45243. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45244. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45245. * 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;
  45246. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45247. */
  45248. set: function (value) {
  45249. this._imageProcessingConfiguration.colorCurves = value;
  45250. },
  45251. enumerable: true,
  45252. configurable: true
  45253. });
  45254. /**
  45255. * Returns the name of this material class.
  45256. */
  45257. PBRMaterial.prototype.getClassName = function () {
  45258. return "PBRMaterial";
  45259. };
  45260. /**
  45261. * Returns an array of the actively used textures.
  45262. * @returns - Array of BaseTextures
  45263. */
  45264. PBRMaterial.prototype.getActiveTextures = function () {
  45265. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45266. if (this._albedoTexture) {
  45267. activeTextures.push(this._albedoTexture);
  45268. }
  45269. if (this._ambientTexture) {
  45270. activeTextures.push(this._ambientTexture);
  45271. }
  45272. if (this._opacityTexture) {
  45273. activeTextures.push(this._opacityTexture);
  45274. }
  45275. if (this._reflectionTexture) {
  45276. activeTextures.push(this._reflectionTexture);
  45277. }
  45278. if (this._emissiveTexture) {
  45279. activeTextures.push(this._emissiveTexture);
  45280. }
  45281. if (this._reflectivityTexture) {
  45282. activeTextures.push(this._reflectivityTexture);
  45283. }
  45284. if (this._metallicTexture) {
  45285. activeTextures.push(this._metallicTexture);
  45286. }
  45287. if (this._microSurfaceTexture) {
  45288. activeTextures.push(this._microSurfaceTexture);
  45289. }
  45290. if (this._bumpTexture) {
  45291. activeTextures.push(this._bumpTexture);
  45292. }
  45293. if (this._lightmapTexture) {
  45294. activeTextures.push(this._lightmapTexture);
  45295. }
  45296. if (this._refractionTexture) {
  45297. activeTextures.push(this._refractionTexture);
  45298. }
  45299. return activeTextures;
  45300. };
  45301. /**
  45302. * Checks to see if a texture is used in the material.
  45303. * @param texture - Base texture to use.
  45304. * @returns - Boolean specifying if a texture is used in the material.
  45305. */
  45306. PBRMaterial.prototype.hasTexture = function (texture) {
  45307. if (_super.prototype.hasTexture.call(this, texture)) {
  45308. return true;
  45309. }
  45310. if (this._albedoTexture === texture) {
  45311. return true;
  45312. }
  45313. if (this._ambientTexture === texture) {
  45314. return true;
  45315. }
  45316. if (this._opacityTexture === texture) {
  45317. return true;
  45318. }
  45319. if (this._reflectionTexture === texture) {
  45320. return true;
  45321. }
  45322. if (this._reflectivityTexture === texture) {
  45323. return true;
  45324. }
  45325. if (this._metallicTexture === texture) {
  45326. return true;
  45327. }
  45328. if (this._microSurfaceTexture === texture) {
  45329. return true;
  45330. }
  45331. if (this._bumpTexture === texture) {
  45332. return true;
  45333. }
  45334. if (this._lightmapTexture === texture) {
  45335. return true;
  45336. }
  45337. if (this._refractionTexture === texture) {
  45338. return true;
  45339. }
  45340. return false;
  45341. };
  45342. /**
  45343. * Makes a duplicate of the current material.
  45344. * @param name - name to use for the new material.
  45345. */
  45346. PBRMaterial.prototype.clone = function (name) {
  45347. var _this = this;
  45348. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45349. clone.id = name;
  45350. clone.name = name;
  45351. return clone;
  45352. };
  45353. /**
  45354. * Serializes this PBR Material.
  45355. * @returns - An object with the serialized material.
  45356. */
  45357. PBRMaterial.prototype.serialize = function () {
  45358. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45359. serializationObject.customType = "BABYLON.PBRMaterial";
  45360. return serializationObject;
  45361. };
  45362. // Statics
  45363. /**
  45364. * Parses a PBR Material from a serialized object.
  45365. * @param source - Serialized object.
  45366. * @param scene - BJS scene instance.
  45367. * @param rootUrl - url for the scene object
  45368. * @returns - PBRMaterial
  45369. */
  45370. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45371. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45372. };
  45373. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45374. /**
  45375. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45376. */
  45377. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45378. /**
  45379. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45380. */
  45381. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45382. /**
  45383. * 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.
  45384. * They are also discarded below the alpha cutoff threshold to improve performances.
  45385. */
  45386. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45387. __decorate([
  45388. BABYLON.serialize(),
  45389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45390. ], PBRMaterial.prototype, "directIntensity", void 0);
  45391. __decorate([
  45392. BABYLON.serialize(),
  45393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45394. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45395. __decorate([
  45396. BABYLON.serialize(),
  45397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45398. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45399. __decorate([
  45400. BABYLON.serialize(),
  45401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45402. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45403. __decorate([
  45404. BABYLON.serialize(),
  45405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45406. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45407. __decorate([
  45408. BABYLON.serializeAsTexture(),
  45409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45410. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45411. __decorate([
  45412. BABYLON.serializeAsTexture(),
  45413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45414. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45415. __decorate([
  45416. BABYLON.serialize(),
  45417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45418. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45419. __decorate([
  45420. BABYLON.serializeAsTexture(),
  45421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45422. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45423. __decorate([
  45424. BABYLON.serializeAsTexture(),
  45425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45426. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45427. __decorate([
  45428. BABYLON.serializeAsTexture(),
  45429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45430. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45431. __decorate([
  45432. BABYLON.serializeAsTexture(),
  45433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45434. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45435. __decorate([
  45436. BABYLON.serializeAsTexture(),
  45437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45438. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45439. __decorate([
  45440. BABYLON.serialize(),
  45441. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45442. ], PBRMaterial.prototype, "metallic", void 0);
  45443. __decorate([
  45444. BABYLON.serialize(),
  45445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45446. ], PBRMaterial.prototype, "roughness", void 0);
  45447. __decorate([
  45448. BABYLON.serializeAsTexture(),
  45449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45450. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45451. __decorate([
  45452. BABYLON.serializeAsTexture(),
  45453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45454. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45455. __decorate([
  45456. BABYLON.serializeAsTexture(),
  45457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45458. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45459. __decorate([
  45460. BABYLON.serializeAsTexture(),
  45461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45462. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45463. __decorate([
  45464. BABYLON.serializeAsColor3("ambient"),
  45465. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45466. ], PBRMaterial.prototype, "ambientColor", void 0);
  45467. __decorate([
  45468. BABYLON.serializeAsColor3("albedo"),
  45469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45470. ], PBRMaterial.prototype, "albedoColor", void 0);
  45471. __decorate([
  45472. BABYLON.serializeAsColor3("reflectivity"),
  45473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45474. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45475. __decorate([
  45476. BABYLON.serializeAsColor3("reflection"),
  45477. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45478. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45479. __decorate([
  45480. BABYLON.serializeAsColor3("emissive"),
  45481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45482. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45483. __decorate([
  45484. BABYLON.serialize(),
  45485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45486. ], PBRMaterial.prototype, "microSurface", void 0);
  45487. __decorate([
  45488. BABYLON.serialize(),
  45489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45490. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45491. __decorate([
  45492. BABYLON.serialize(),
  45493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45494. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45495. __decorate([
  45496. BABYLON.serialize(),
  45497. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45498. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45499. __decorate([
  45500. BABYLON.serialize(),
  45501. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45502. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45503. __decorate([
  45504. BABYLON.serialize(),
  45505. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45506. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45507. __decorate([
  45508. BABYLON.serialize(),
  45509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45510. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45511. __decorate([
  45512. BABYLON.serialize(),
  45513. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45514. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45515. __decorate([
  45516. BABYLON.serialize(),
  45517. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45518. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45519. __decorate([
  45520. BABYLON.serialize(),
  45521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45522. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45523. __decorate([
  45524. BABYLON.serialize(),
  45525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45526. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45527. __decorate([
  45528. BABYLON.serialize(),
  45529. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45530. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45531. __decorate([
  45532. BABYLON.serialize(),
  45533. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45534. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45535. __decorate([
  45536. BABYLON.serialize(),
  45537. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45538. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45539. __decorate([
  45540. BABYLON.serialize(),
  45541. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45542. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45543. __decorate([
  45544. BABYLON.serialize(),
  45545. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45546. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45547. __decorate([
  45548. BABYLON.serialize(),
  45549. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45550. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45551. __decorate([
  45552. BABYLON.serialize(),
  45553. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45554. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45555. __decorate([
  45556. BABYLON.serialize(),
  45557. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45558. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45559. __decorate([
  45560. BABYLON.serialize(),
  45561. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45562. ], PBRMaterial.prototype, "useParallax", void 0);
  45563. __decorate([
  45564. BABYLON.serialize(),
  45565. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45566. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45567. __decorate([
  45568. BABYLON.serialize(),
  45569. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45570. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45571. __decorate([
  45572. BABYLON.serialize(),
  45573. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45574. ], PBRMaterial.prototype, "disableLighting", void 0);
  45575. __decorate([
  45576. BABYLON.serialize(),
  45577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45578. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45579. __decorate([
  45580. BABYLON.serialize(),
  45581. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45582. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45583. __decorate([
  45584. BABYLON.serialize(),
  45585. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45586. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45587. __decorate([
  45588. BABYLON.serialize(),
  45589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45590. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45591. __decorate([
  45592. BABYLON.serialize(),
  45593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45594. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45595. __decorate([
  45596. BABYLON.serialize(),
  45597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45598. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45599. __decorate([
  45600. BABYLON.serialize(),
  45601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45602. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45603. __decorate([
  45604. BABYLON.serializeAsTexture(),
  45605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45606. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45607. __decorate([
  45608. BABYLON.serialize(),
  45609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45610. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45611. __decorate([
  45612. BABYLON.serialize(),
  45613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45614. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45615. __decorate([
  45616. BABYLON.serialize(),
  45617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45618. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45619. __decorate([
  45620. BABYLON.serialize(),
  45621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45622. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45623. __decorate([
  45624. BABYLON.serialize(),
  45625. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45626. ], PBRMaterial.prototype, "unlit", void 0);
  45627. return PBRMaterial;
  45628. }(BABYLON.PBRBaseMaterial));
  45629. BABYLON.PBRMaterial = PBRMaterial;
  45630. })(BABYLON || (BABYLON = {}));
  45631. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45632. var BABYLON;
  45633. (function (BABYLON) {
  45634. /**
  45635. * The PBR material of BJS following the metal roughness convention.
  45636. *
  45637. * This fits to the PBR convention in the GLTF definition:
  45638. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45639. */
  45640. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45641. __extends(PBRMetallicRoughnessMaterial, _super);
  45642. /**
  45643. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45644. *
  45645. * @param name The material name
  45646. * @param scene The scene the material will be use in.
  45647. */
  45648. function PBRMetallicRoughnessMaterial(name, scene) {
  45649. var _this = _super.call(this, name, scene) || this;
  45650. _this._useRoughnessFromMetallicTextureAlpha = false;
  45651. _this._useRoughnessFromMetallicTextureGreen = true;
  45652. _this._useMetallnessFromMetallicTextureBlue = true;
  45653. _this.metallic = 1.0;
  45654. _this.roughness = 1.0;
  45655. return _this;
  45656. }
  45657. /**
  45658. * Return the currrent class name of the material.
  45659. */
  45660. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45661. return "PBRMetallicRoughnessMaterial";
  45662. };
  45663. /**
  45664. * Return the active textures of the material.
  45665. */
  45666. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45667. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45668. if (this.baseTexture) {
  45669. activeTextures.push(this.baseTexture);
  45670. }
  45671. if (this.metallicRoughnessTexture) {
  45672. activeTextures.push(this.metallicRoughnessTexture);
  45673. }
  45674. return activeTextures;
  45675. };
  45676. /**
  45677. * Checks to see if a texture is used in the material.
  45678. * @param texture - Base texture to use.
  45679. * @returns - Boolean specifying if a texture is used in the material.
  45680. */
  45681. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45682. if (_super.prototype.hasTexture.call(this, texture)) {
  45683. return true;
  45684. }
  45685. if (this.baseTexture === texture) {
  45686. return true;
  45687. }
  45688. if (this.metallicRoughnessTexture === texture) {
  45689. return true;
  45690. }
  45691. return false;
  45692. };
  45693. /**
  45694. * Makes a duplicate of the current material.
  45695. * @param name - name to use for the new material.
  45696. */
  45697. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45698. var _this = this;
  45699. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45700. clone.id = name;
  45701. clone.name = name;
  45702. return clone;
  45703. };
  45704. /**
  45705. * Serialize the material to a parsable JSON object.
  45706. */
  45707. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45708. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45709. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45710. return serializationObject;
  45711. };
  45712. /**
  45713. * Parses a JSON object correponding to the serialize function.
  45714. */
  45715. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45716. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45717. };
  45718. __decorate([
  45719. BABYLON.serializeAsColor3(),
  45720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45721. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45722. __decorate([
  45723. BABYLON.serializeAsTexture(),
  45724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45725. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45726. __decorate([
  45727. BABYLON.serialize(),
  45728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45729. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45730. __decorate([
  45731. BABYLON.serialize(),
  45732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45733. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45734. __decorate([
  45735. BABYLON.serializeAsTexture(),
  45736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45737. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45738. return PBRMetallicRoughnessMaterial;
  45739. }(BABYLON.PBRBaseSimpleMaterial));
  45740. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45741. })(BABYLON || (BABYLON = {}));
  45742. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45743. var BABYLON;
  45744. (function (BABYLON) {
  45745. /**
  45746. * The PBR material of BJS following the specular glossiness convention.
  45747. *
  45748. * This fits to the PBR convention in the GLTF definition:
  45749. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45750. */
  45751. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45752. __extends(PBRSpecularGlossinessMaterial, _super);
  45753. /**
  45754. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45755. *
  45756. * @param name The material name
  45757. * @param scene The scene the material will be use in.
  45758. */
  45759. function PBRSpecularGlossinessMaterial(name, scene) {
  45760. var _this = _super.call(this, name, scene) || this;
  45761. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45762. return _this;
  45763. }
  45764. /**
  45765. * Return the currrent class name of the material.
  45766. */
  45767. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45768. return "PBRSpecularGlossinessMaterial";
  45769. };
  45770. /**
  45771. * Return the active textures of the material.
  45772. */
  45773. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45774. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45775. if (this.diffuseTexture) {
  45776. activeTextures.push(this.diffuseTexture);
  45777. }
  45778. if (this.specularGlossinessTexture) {
  45779. activeTextures.push(this.specularGlossinessTexture);
  45780. }
  45781. return activeTextures;
  45782. };
  45783. /**
  45784. * Checks to see if a texture is used in the material.
  45785. * @param texture - Base texture to use.
  45786. * @returns - Boolean specifying if a texture is used in the material.
  45787. */
  45788. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45789. if (_super.prototype.hasTexture.call(this, texture)) {
  45790. return true;
  45791. }
  45792. if (this.diffuseTexture === texture) {
  45793. return true;
  45794. }
  45795. if (this.specularGlossinessTexture === texture) {
  45796. return true;
  45797. }
  45798. return false;
  45799. };
  45800. /**
  45801. * Makes a duplicate of the current material.
  45802. * @param name - name to use for the new material.
  45803. */
  45804. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45805. var _this = this;
  45806. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45807. clone.id = name;
  45808. clone.name = name;
  45809. return clone;
  45810. };
  45811. /**
  45812. * Serialize the material to a parsable JSON object.
  45813. */
  45814. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45815. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45816. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45817. return serializationObject;
  45818. };
  45819. /**
  45820. * Parses a JSON object correponding to the serialize function.
  45821. */
  45822. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45823. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45824. };
  45825. __decorate([
  45826. BABYLON.serializeAsColor3("diffuse"),
  45827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45828. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45829. __decorate([
  45830. BABYLON.serializeAsTexture(),
  45831. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45832. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45833. __decorate([
  45834. BABYLON.serializeAsColor3("specular"),
  45835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45836. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45837. __decorate([
  45838. BABYLON.serialize(),
  45839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45840. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45841. __decorate([
  45842. BABYLON.serializeAsTexture(),
  45843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45844. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45845. return PBRSpecularGlossinessMaterial;
  45846. }(BABYLON.PBRBaseSimpleMaterial));
  45847. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45848. })(BABYLON || (BABYLON = {}));
  45849. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45850. var BABYLON;
  45851. (function (BABYLON) {
  45852. BABYLON.CameraInputTypes = {};
  45853. var CameraInputsManager = /** @class */ (function () {
  45854. function CameraInputsManager(camera) {
  45855. this.attached = {};
  45856. this.camera = camera;
  45857. this.checkInputs = function () { };
  45858. }
  45859. /**
  45860. * Add an input method to a camera.
  45861. * builtin inputs example: camera.inputs.addGamepad();
  45862. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  45863. * @param input camera input method
  45864. */
  45865. CameraInputsManager.prototype.add = function (input) {
  45866. var type = input.getSimpleName();
  45867. if (this.attached[type]) {
  45868. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45869. return;
  45870. }
  45871. this.attached[type] = input;
  45872. input.camera = this.camera;
  45873. //for checkInputs, we are dynamically creating a function
  45874. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45875. if (input.checkInputs) {
  45876. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45877. }
  45878. if (this.attachedElement) {
  45879. input.attachControl(this.attachedElement);
  45880. }
  45881. };
  45882. /**
  45883. * Remove a specific input method from a camera
  45884. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45885. * @param inputToRemove camera input method
  45886. */
  45887. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45888. for (var cam in this.attached) {
  45889. var input = this.attached[cam];
  45890. if (input === inputToRemove) {
  45891. input.detachControl(this.attachedElement);
  45892. input.camera = null;
  45893. delete this.attached[cam];
  45894. this.rebuildInputCheck();
  45895. }
  45896. }
  45897. };
  45898. CameraInputsManager.prototype.removeByType = function (inputType) {
  45899. for (var cam in this.attached) {
  45900. var input = this.attached[cam];
  45901. if (input.getClassName() === inputType) {
  45902. input.detachControl(this.attachedElement);
  45903. input.camera = null;
  45904. delete this.attached[cam];
  45905. this.rebuildInputCheck();
  45906. }
  45907. }
  45908. };
  45909. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45910. var current = this.checkInputs;
  45911. return function () {
  45912. current();
  45913. fn();
  45914. };
  45915. };
  45916. CameraInputsManager.prototype.attachInput = function (input) {
  45917. if (this.attachedElement) {
  45918. input.attachControl(this.attachedElement, this.noPreventDefault);
  45919. }
  45920. };
  45921. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45922. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45923. if (this.attachedElement) {
  45924. return;
  45925. }
  45926. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45927. this.attachedElement = element;
  45928. this.noPreventDefault = noPreventDefault;
  45929. for (var cam in this.attached) {
  45930. this.attached[cam].attachControl(element, noPreventDefault);
  45931. }
  45932. };
  45933. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  45934. if (disconnect === void 0) { disconnect = false; }
  45935. if (this.attachedElement !== element) {
  45936. return;
  45937. }
  45938. for (var cam in this.attached) {
  45939. this.attached[cam].detachControl(element);
  45940. if (disconnect) {
  45941. this.attached[cam].camera = null;
  45942. }
  45943. }
  45944. this.attachedElement = null;
  45945. };
  45946. CameraInputsManager.prototype.rebuildInputCheck = function () {
  45947. this.checkInputs = function () { };
  45948. for (var cam in this.attached) {
  45949. var input = this.attached[cam];
  45950. if (input.checkInputs) {
  45951. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45952. }
  45953. }
  45954. };
  45955. /**
  45956. * Remove all attached input methods from a camera
  45957. */
  45958. CameraInputsManager.prototype.clear = function () {
  45959. if (this.attachedElement) {
  45960. this.detachElement(this.attachedElement, true);
  45961. }
  45962. this.attached = {};
  45963. this.attachedElement = null;
  45964. this.checkInputs = function () { };
  45965. };
  45966. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  45967. var inputs = {};
  45968. for (var cam in this.attached) {
  45969. var input = this.attached[cam];
  45970. var res = BABYLON.SerializationHelper.Serialize(input);
  45971. inputs[input.getClassName()] = res;
  45972. }
  45973. serializedCamera.inputsmgr = inputs;
  45974. };
  45975. CameraInputsManager.prototype.parse = function (parsedCamera) {
  45976. var parsedInputs = parsedCamera.inputsmgr;
  45977. if (parsedInputs) {
  45978. this.clear();
  45979. for (var n in parsedInputs) {
  45980. var construct = BABYLON.CameraInputTypes[n];
  45981. if (construct) {
  45982. var parsedinput = parsedInputs[n];
  45983. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  45984. this.add(input);
  45985. }
  45986. }
  45987. }
  45988. else {
  45989. //2016-03-08 this part is for managing backward compatibility
  45990. for (var n in this.attached) {
  45991. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  45992. if (construct) {
  45993. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  45994. this.remove(this.attached[n]);
  45995. this.add(input);
  45996. }
  45997. }
  45998. }
  45999. };
  46000. return CameraInputsManager;
  46001. }());
  46002. BABYLON.CameraInputsManager = CameraInputsManager;
  46003. })(BABYLON || (BABYLON = {}));
  46004. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46005. var BABYLON;
  46006. (function (BABYLON) {
  46007. var TargetCamera = /** @class */ (function (_super) {
  46008. __extends(TargetCamera, _super);
  46009. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46010. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46011. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46012. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46013. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46014. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46015. _this.speed = 2.0;
  46016. _this.noRotationConstraint = false;
  46017. _this.lockedTarget = null;
  46018. _this._currentTarget = BABYLON.Vector3.Zero();
  46019. _this._viewMatrix = BABYLON.Matrix.Zero();
  46020. _this._camMatrix = BABYLON.Matrix.Zero();
  46021. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46022. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46023. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46024. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46025. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46026. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46027. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46028. return _this;
  46029. }
  46030. TargetCamera.prototype.getFrontPosition = function (distance) {
  46031. this.getWorldMatrix();
  46032. var direction = this.getTarget().subtract(this.position);
  46033. direction.normalize();
  46034. direction.scaleInPlace(distance);
  46035. return this.globalPosition.add(direction);
  46036. };
  46037. TargetCamera.prototype._getLockedTargetPosition = function () {
  46038. if (!this.lockedTarget) {
  46039. return null;
  46040. }
  46041. if (this.lockedTarget.absolutePosition) {
  46042. this.lockedTarget.computeWorldMatrix();
  46043. }
  46044. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46045. };
  46046. TargetCamera.prototype.storeState = function () {
  46047. this._storedPosition = this.position.clone();
  46048. this._storedRotation = this.rotation.clone();
  46049. if (this.rotationQuaternion) {
  46050. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46051. }
  46052. return _super.prototype.storeState.call(this);
  46053. };
  46054. /**
  46055. * Restored camera state. You must call storeState() first
  46056. */
  46057. TargetCamera.prototype._restoreStateValues = function () {
  46058. if (!_super.prototype._restoreStateValues.call(this)) {
  46059. return false;
  46060. }
  46061. this.position = this._storedPosition.clone();
  46062. this.rotation = this._storedRotation.clone();
  46063. if (this.rotationQuaternion) {
  46064. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46065. }
  46066. this.cameraDirection.copyFromFloats(0, 0, 0);
  46067. this.cameraRotation.copyFromFloats(0, 0);
  46068. return true;
  46069. };
  46070. // Cache
  46071. TargetCamera.prototype._initCache = function () {
  46072. _super.prototype._initCache.call(this);
  46073. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46074. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46075. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46076. };
  46077. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46078. if (!ignoreParentClass) {
  46079. _super.prototype._updateCache.call(this);
  46080. }
  46081. var lockedTargetPosition = this._getLockedTargetPosition();
  46082. if (!lockedTargetPosition) {
  46083. this._cache.lockedTarget = null;
  46084. }
  46085. else {
  46086. if (!this._cache.lockedTarget) {
  46087. this._cache.lockedTarget = lockedTargetPosition.clone();
  46088. }
  46089. else {
  46090. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46091. }
  46092. }
  46093. this._cache.rotation.copyFrom(this.rotation);
  46094. if (this.rotationQuaternion)
  46095. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46096. };
  46097. // Synchronized
  46098. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46099. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46100. return false;
  46101. }
  46102. var lockedTargetPosition = this._getLockedTargetPosition();
  46103. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46104. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46105. };
  46106. // Methods
  46107. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46108. var engine = this.getEngine();
  46109. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46110. };
  46111. // Target
  46112. TargetCamera.prototype.setTarget = function (target) {
  46113. this.upVector.normalize();
  46114. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46115. this._camMatrix.invert();
  46116. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46117. var vDir = target.subtract(this.position);
  46118. if (vDir.x >= 0.0) {
  46119. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46120. }
  46121. else {
  46122. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46123. }
  46124. this.rotation.z = 0;
  46125. if (isNaN(this.rotation.x)) {
  46126. this.rotation.x = 0;
  46127. }
  46128. if (isNaN(this.rotation.y)) {
  46129. this.rotation.y = 0;
  46130. }
  46131. if (isNaN(this.rotation.z)) {
  46132. this.rotation.z = 0;
  46133. }
  46134. if (this.rotationQuaternion) {
  46135. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46136. }
  46137. };
  46138. /**
  46139. * Return the current target position of the camera. This value is expressed in local space.
  46140. */
  46141. TargetCamera.prototype.getTarget = function () {
  46142. return this._currentTarget;
  46143. };
  46144. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46145. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46146. };
  46147. TargetCamera.prototype._updatePosition = function () {
  46148. if (this.parent) {
  46149. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46150. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46151. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46152. return;
  46153. }
  46154. this.position.addInPlace(this.cameraDirection);
  46155. };
  46156. TargetCamera.prototype._checkInputs = function () {
  46157. var needToMove = this._decideIfNeedsToMove();
  46158. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46159. // Move
  46160. if (needToMove) {
  46161. this._updatePosition();
  46162. }
  46163. // Rotate
  46164. if (needToRotate) {
  46165. this.rotation.x += this.cameraRotation.x;
  46166. this.rotation.y += this.cameraRotation.y;
  46167. //rotate, if quaternion is set and rotation was used
  46168. if (this.rotationQuaternion) {
  46169. var len = this.rotation.lengthSquared();
  46170. if (len) {
  46171. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46172. }
  46173. }
  46174. if (!this.noRotationConstraint) {
  46175. var limit = (Math.PI / 2) * 0.95;
  46176. if (this.rotation.x > limit)
  46177. this.rotation.x = limit;
  46178. if (this.rotation.x < -limit)
  46179. this.rotation.x = -limit;
  46180. }
  46181. }
  46182. // Inertia
  46183. if (needToMove) {
  46184. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46185. this.cameraDirection.x = 0;
  46186. }
  46187. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46188. this.cameraDirection.y = 0;
  46189. }
  46190. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46191. this.cameraDirection.z = 0;
  46192. }
  46193. this.cameraDirection.scaleInPlace(this.inertia);
  46194. }
  46195. if (needToRotate) {
  46196. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46197. this.cameraRotation.x = 0;
  46198. }
  46199. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46200. this.cameraRotation.y = 0;
  46201. }
  46202. this.cameraRotation.scaleInPlace(this.inertia);
  46203. }
  46204. _super.prototype._checkInputs.call(this);
  46205. };
  46206. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46207. if (this.rotationQuaternion) {
  46208. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46209. }
  46210. else {
  46211. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46212. }
  46213. //update the up vector!
  46214. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46215. };
  46216. TargetCamera.prototype._getViewMatrix = function () {
  46217. if (this.lockedTarget) {
  46218. this.setTarget(this._getLockedTargetPosition());
  46219. }
  46220. // Compute
  46221. this._updateCameraRotationMatrix();
  46222. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46223. // Computing target and final matrix
  46224. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46225. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  46226. return this._viewMatrix;
  46227. };
  46228. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46229. if (this.parent) {
  46230. var parentWorldMatrix = this.parent.getWorldMatrix();
  46231. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  46232. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46233. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46234. this._markSyncedWithParent();
  46235. }
  46236. else {
  46237. this._globalPosition.copyFrom(this.position);
  46238. this._globalCurrentTarget.copyFrom(target);
  46239. this._globalCurrentUpVector.copyFrom(up);
  46240. }
  46241. if (this.getScene().useRightHandedSystem) {
  46242. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46243. }
  46244. else {
  46245. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46246. }
  46247. };
  46248. /**
  46249. * @override
  46250. * Override Camera.createRigCamera
  46251. */
  46252. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46253. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46254. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46255. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46256. if (!this.rotationQuaternion) {
  46257. this.rotationQuaternion = new BABYLON.Quaternion();
  46258. }
  46259. rigCamera._cameraRigParams = {};
  46260. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46261. }
  46262. return rigCamera;
  46263. }
  46264. return null;
  46265. };
  46266. /**
  46267. * @override
  46268. * Override Camera._updateRigCameras
  46269. */
  46270. TargetCamera.prototype._updateRigCameras = function () {
  46271. var camLeft = this._rigCameras[0];
  46272. var camRight = this._rigCameras[1];
  46273. switch (this.cameraRigMode) {
  46274. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46275. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46276. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46277. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46278. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46279. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46280. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46281. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46282. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46283. camLeft.setTarget(this.getTarget());
  46284. camRight.setTarget(this.getTarget());
  46285. break;
  46286. case BABYLON.Camera.RIG_MODE_VR:
  46287. if (camLeft.rotationQuaternion) {
  46288. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46289. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46290. }
  46291. else {
  46292. camLeft.rotation.copyFrom(this.rotation);
  46293. camRight.rotation.copyFrom(this.rotation);
  46294. }
  46295. camLeft.position.copyFrom(this.position);
  46296. camRight.position.copyFrom(this.position);
  46297. break;
  46298. }
  46299. _super.prototype._updateRigCameras.call(this);
  46300. };
  46301. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46302. if (!this._rigCamTransformMatrix) {
  46303. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46304. }
  46305. var target = this.getTarget();
  46306. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46307. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46308. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46309. };
  46310. TargetCamera.prototype.getClassName = function () {
  46311. return "TargetCamera";
  46312. };
  46313. __decorate([
  46314. BABYLON.serializeAsVector3()
  46315. ], TargetCamera.prototype, "rotation", void 0);
  46316. __decorate([
  46317. BABYLON.serialize()
  46318. ], TargetCamera.prototype, "speed", void 0);
  46319. __decorate([
  46320. BABYLON.serializeAsMeshReference("lockedTargetId")
  46321. ], TargetCamera.prototype, "lockedTarget", void 0);
  46322. return TargetCamera;
  46323. }(BABYLON.Camera));
  46324. BABYLON.TargetCamera = TargetCamera;
  46325. })(BABYLON || (BABYLON = {}));
  46326. //# sourceMappingURL=babylon.targetCamera.js.map
  46327. var BABYLON;
  46328. (function (BABYLON) {
  46329. var FreeCameraMouseInput = /** @class */ (function () {
  46330. function FreeCameraMouseInput(touchEnabled) {
  46331. if (touchEnabled === void 0) { touchEnabled = true; }
  46332. this.touchEnabled = touchEnabled;
  46333. this.buttons = [0, 1, 2];
  46334. this.angularSensibility = 2000.0;
  46335. this.previousPosition = null;
  46336. }
  46337. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46338. var _this = this;
  46339. var engine = this.camera.getEngine();
  46340. if (!this._pointerInput) {
  46341. this._pointerInput = function (p, s) {
  46342. var evt = p.event;
  46343. if (engine.isInVRExclusivePointerMode) {
  46344. return;
  46345. }
  46346. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46347. return;
  46348. }
  46349. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46350. return;
  46351. }
  46352. var srcElement = (evt.srcElement || evt.target);
  46353. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46354. try {
  46355. srcElement.setPointerCapture(evt.pointerId);
  46356. }
  46357. catch (e) {
  46358. //Nothing to do with the error. Execution will continue.
  46359. }
  46360. _this.previousPosition = {
  46361. x: evt.clientX,
  46362. y: evt.clientY
  46363. };
  46364. if (!noPreventDefault) {
  46365. evt.preventDefault();
  46366. element.focus();
  46367. }
  46368. }
  46369. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46370. try {
  46371. srcElement.releasePointerCapture(evt.pointerId);
  46372. }
  46373. catch (e) {
  46374. //Nothing to do with the error.
  46375. }
  46376. _this.previousPosition = null;
  46377. if (!noPreventDefault) {
  46378. evt.preventDefault();
  46379. }
  46380. }
  46381. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46382. if (!_this.previousPosition || engine.isPointerLock) {
  46383. return;
  46384. }
  46385. var offsetX = evt.clientX - _this.previousPosition.x;
  46386. if (_this.camera.getScene().useRightHandedSystem)
  46387. offsetX *= -1;
  46388. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46389. offsetX *= -1;
  46390. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46391. var offsetY = evt.clientY - _this.previousPosition.y;
  46392. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46393. _this.previousPosition = {
  46394. x: evt.clientX,
  46395. y: evt.clientY
  46396. };
  46397. if (!noPreventDefault) {
  46398. evt.preventDefault();
  46399. }
  46400. }
  46401. };
  46402. }
  46403. this._onMouseMove = function (evt) {
  46404. if (!engine.isPointerLock) {
  46405. return;
  46406. }
  46407. if (engine.isInVRExclusivePointerMode) {
  46408. return;
  46409. }
  46410. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46411. if (_this.camera.getScene().useRightHandedSystem)
  46412. offsetX *= -1;
  46413. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46414. offsetX *= -1;
  46415. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46416. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46417. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46418. _this.previousPosition = null;
  46419. if (!noPreventDefault) {
  46420. evt.preventDefault();
  46421. }
  46422. };
  46423. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46424. element.addEventListener("mousemove", this._onMouseMove, false);
  46425. };
  46426. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46427. if (this._observer && element) {
  46428. this.camera.getScene().onPointerObservable.remove(this._observer);
  46429. if (this._onMouseMove) {
  46430. element.removeEventListener("mousemove", this._onMouseMove);
  46431. }
  46432. this._observer = null;
  46433. this._onMouseMove = null;
  46434. this.previousPosition = null;
  46435. }
  46436. };
  46437. FreeCameraMouseInput.prototype.getClassName = function () {
  46438. return "FreeCameraMouseInput";
  46439. };
  46440. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46441. return "mouse";
  46442. };
  46443. __decorate([
  46444. BABYLON.serialize()
  46445. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46446. __decorate([
  46447. BABYLON.serialize()
  46448. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46449. return FreeCameraMouseInput;
  46450. }());
  46451. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46452. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46453. })(BABYLON || (BABYLON = {}));
  46454. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46455. var BABYLON;
  46456. (function (BABYLON) {
  46457. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46458. function FreeCameraKeyboardMoveInput() {
  46459. this._keys = new Array();
  46460. this.keysUp = [38];
  46461. this.keysDown = [40];
  46462. this.keysLeft = [37];
  46463. this.keysRight = [39];
  46464. }
  46465. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46466. var _this = this;
  46467. if (this._onCanvasBlurObserver) {
  46468. return;
  46469. }
  46470. this._scene = this.camera.getScene();
  46471. this._engine = this._scene.getEngine();
  46472. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46473. _this._keys = [];
  46474. });
  46475. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46476. var evt = info.event;
  46477. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46478. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46479. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46480. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46481. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46482. var index = _this._keys.indexOf(evt.keyCode);
  46483. if (index === -1) {
  46484. _this._keys.push(evt.keyCode);
  46485. }
  46486. if (!noPreventDefault) {
  46487. evt.preventDefault();
  46488. }
  46489. }
  46490. }
  46491. else {
  46492. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46493. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46494. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46495. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46496. var index = _this._keys.indexOf(evt.keyCode);
  46497. if (index >= 0) {
  46498. _this._keys.splice(index, 1);
  46499. }
  46500. if (!noPreventDefault) {
  46501. evt.preventDefault();
  46502. }
  46503. }
  46504. }
  46505. });
  46506. };
  46507. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46508. if (this._scene) {
  46509. if (this._onKeyboardObserver) {
  46510. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46511. }
  46512. if (this._onCanvasBlurObserver) {
  46513. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46514. }
  46515. this._onKeyboardObserver = null;
  46516. this._onCanvasBlurObserver = null;
  46517. }
  46518. this._keys = [];
  46519. };
  46520. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46521. if (this._onKeyboardObserver) {
  46522. var camera = this.camera;
  46523. // Keyboard
  46524. for (var index = 0; index < this._keys.length; index++) {
  46525. var keyCode = this._keys[index];
  46526. var speed = camera._computeLocalCameraSpeed();
  46527. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46528. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46529. }
  46530. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46531. camera._localDirection.copyFromFloats(0, 0, speed);
  46532. }
  46533. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46534. camera._localDirection.copyFromFloats(speed, 0, 0);
  46535. }
  46536. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46537. camera._localDirection.copyFromFloats(0, 0, -speed);
  46538. }
  46539. if (camera.getScene().useRightHandedSystem) {
  46540. camera._localDirection.z *= -1;
  46541. }
  46542. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46543. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46544. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46545. }
  46546. }
  46547. };
  46548. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46549. return "FreeCameraKeyboardMoveInput";
  46550. };
  46551. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46552. this._keys = [];
  46553. };
  46554. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46555. return "keyboard";
  46556. };
  46557. __decorate([
  46558. BABYLON.serialize()
  46559. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46560. __decorate([
  46561. BABYLON.serialize()
  46562. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46563. __decorate([
  46564. BABYLON.serialize()
  46565. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46566. __decorate([
  46567. BABYLON.serialize()
  46568. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46569. return FreeCameraKeyboardMoveInput;
  46570. }());
  46571. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46572. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46573. })(BABYLON || (BABYLON = {}));
  46574. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46575. var BABYLON;
  46576. (function (BABYLON) {
  46577. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46578. __extends(FreeCameraInputsManager, _super);
  46579. function FreeCameraInputsManager(camera) {
  46580. return _super.call(this, camera) || this;
  46581. }
  46582. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46583. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46584. return this;
  46585. };
  46586. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46587. if (touchEnabled === void 0) { touchEnabled = true; }
  46588. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46589. return this;
  46590. };
  46591. FreeCameraInputsManager.prototype.addGamepad = function () {
  46592. this.add(new BABYLON.FreeCameraGamepadInput());
  46593. return this;
  46594. };
  46595. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46596. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46597. return this;
  46598. };
  46599. FreeCameraInputsManager.prototype.addTouch = function () {
  46600. this.add(new BABYLON.FreeCameraTouchInput());
  46601. return this;
  46602. };
  46603. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46604. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46605. return this;
  46606. };
  46607. return FreeCameraInputsManager;
  46608. }(BABYLON.CameraInputsManager));
  46609. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46610. })(BABYLON || (BABYLON = {}));
  46611. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46612. var BABYLON;
  46613. (function (BABYLON) {
  46614. var FreeCamera = /** @class */ (function (_super) {
  46615. __extends(FreeCamera, _super);
  46616. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46617. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46618. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46619. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46620. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46621. _this.checkCollisions = false;
  46622. _this.applyGravity = false;
  46623. _this._needMoveForGravity = false;
  46624. _this._oldPosition = BABYLON.Vector3.Zero();
  46625. _this._diffPosition = BABYLON.Vector3.Zero();
  46626. _this._newPosition = BABYLON.Vector3.Zero();
  46627. // Collisions
  46628. _this._collisionMask = -1;
  46629. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46630. if (collidedMesh === void 0) { collidedMesh = null; }
  46631. //TODO move this to the collision coordinator!
  46632. if (_this.getScene().workerCollisions)
  46633. newPosition.multiplyInPlace(_this._collider._radius);
  46634. var updatePosition = function (newPos) {
  46635. _this._newPosition.copyFrom(newPos);
  46636. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46637. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46638. _this.position.addInPlace(_this._diffPosition);
  46639. if (_this.onCollide && collidedMesh) {
  46640. _this.onCollide(collidedMesh);
  46641. }
  46642. }
  46643. };
  46644. updatePosition(newPosition);
  46645. };
  46646. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46647. _this.inputs.addKeyboard().addMouse();
  46648. return _this;
  46649. }
  46650. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46651. //-- begin properties for backward compatibility for inputs
  46652. /**
  46653. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46654. * Higher values reduce sensitivity.
  46655. */
  46656. get: function () {
  46657. var mouse = this.inputs.attached["mouse"];
  46658. if (mouse)
  46659. return mouse.angularSensibility;
  46660. return 0;
  46661. },
  46662. /**
  46663. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46664. * Higher values reduce sensitivity.
  46665. */
  46666. set: function (value) {
  46667. var mouse = this.inputs.attached["mouse"];
  46668. if (mouse)
  46669. mouse.angularSensibility = value;
  46670. },
  46671. enumerable: true,
  46672. configurable: true
  46673. });
  46674. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46675. get: function () {
  46676. var keyboard = this.inputs.attached["keyboard"];
  46677. if (keyboard)
  46678. return keyboard.keysUp;
  46679. return [];
  46680. },
  46681. set: function (value) {
  46682. var keyboard = this.inputs.attached["keyboard"];
  46683. if (keyboard)
  46684. keyboard.keysUp = value;
  46685. },
  46686. enumerable: true,
  46687. configurable: true
  46688. });
  46689. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46690. get: function () {
  46691. var keyboard = this.inputs.attached["keyboard"];
  46692. if (keyboard)
  46693. return keyboard.keysDown;
  46694. return [];
  46695. },
  46696. set: function (value) {
  46697. var keyboard = this.inputs.attached["keyboard"];
  46698. if (keyboard)
  46699. keyboard.keysDown = value;
  46700. },
  46701. enumerable: true,
  46702. configurable: true
  46703. });
  46704. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46705. get: function () {
  46706. var keyboard = this.inputs.attached["keyboard"];
  46707. if (keyboard)
  46708. return keyboard.keysLeft;
  46709. return [];
  46710. },
  46711. set: function (value) {
  46712. var keyboard = this.inputs.attached["keyboard"];
  46713. if (keyboard)
  46714. keyboard.keysLeft = value;
  46715. },
  46716. enumerable: true,
  46717. configurable: true
  46718. });
  46719. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46720. get: function () {
  46721. var keyboard = this.inputs.attached["keyboard"];
  46722. if (keyboard)
  46723. return keyboard.keysRight;
  46724. return [];
  46725. },
  46726. set: function (value) {
  46727. var keyboard = this.inputs.attached["keyboard"];
  46728. if (keyboard)
  46729. keyboard.keysRight = value;
  46730. },
  46731. enumerable: true,
  46732. configurable: true
  46733. });
  46734. // Controls
  46735. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46736. this.inputs.attachElement(element, noPreventDefault);
  46737. };
  46738. FreeCamera.prototype.detachControl = function (element) {
  46739. this.inputs.detachElement(element);
  46740. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46741. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46742. };
  46743. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46744. get: function () {
  46745. return this._collisionMask;
  46746. },
  46747. set: function (mask) {
  46748. this._collisionMask = !isNaN(mask) ? mask : -1;
  46749. },
  46750. enumerable: true,
  46751. configurable: true
  46752. });
  46753. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46754. var globalPosition;
  46755. if (this.parent) {
  46756. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46757. }
  46758. else {
  46759. globalPosition = this.position;
  46760. }
  46761. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46762. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46763. if (!this._collider) {
  46764. this._collider = new BABYLON.Collider();
  46765. }
  46766. this._collider._radius = this.ellipsoid;
  46767. this._collider.collisionMask = this._collisionMask;
  46768. //no need for clone, as long as gravity is not on.
  46769. var actualDisplacement = displacement;
  46770. //add gravity to the direction to prevent the dual-collision checking
  46771. if (this.applyGravity) {
  46772. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46773. actualDisplacement = displacement.add(this.getScene().gravity);
  46774. }
  46775. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46776. };
  46777. FreeCamera.prototype._checkInputs = function () {
  46778. if (!this._localDirection) {
  46779. this._localDirection = BABYLON.Vector3.Zero();
  46780. this._transformedDirection = BABYLON.Vector3.Zero();
  46781. }
  46782. this.inputs.checkInputs();
  46783. _super.prototype._checkInputs.call(this);
  46784. };
  46785. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46786. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46787. };
  46788. FreeCamera.prototype._updatePosition = function () {
  46789. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46790. this._collideWithWorld(this.cameraDirection);
  46791. }
  46792. else {
  46793. _super.prototype._updatePosition.call(this);
  46794. }
  46795. };
  46796. FreeCamera.prototype.dispose = function () {
  46797. this.inputs.clear();
  46798. _super.prototype.dispose.call(this);
  46799. };
  46800. FreeCamera.prototype.getClassName = function () {
  46801. return "FreeCamera";
  46802. };
  46803. __decorate([
  46804. BABYLON.serializeAsVector3()
  46805. ], FreeCamera.prototype, "ellipsoid", void 0);
  46806. __decorate([
  46807. BABYLON.serializeAsVector3()
  46808. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46809. __decorate([
  46810. BABYLON.serialize()
  46811. ], FreeCamera.prototype, "checkCollisions", void 0);
  46812. __decorate([
  46813. BABYLON.serialize()
  46814. ], FreeCamera.prototype, "applyGravity", void 0);
  46815. return FreeCamera;
  46816. }(BABYLON.TargetCamera));
  46817. BABYLON.FreeCamera = FreeCamera;
  46818. })(BABYLON || (BABYLON = {}));
  46819. //# sourceMappingURL=babylon.freeCamera.js.map
  46820. var BABYLON;
  46821. (function (BABYLON) {
  46822. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46823. function ArcRotateCameraKeyboardMoveInput() {
  46824. this._keys = new Array();
  46825. this.keysUp = [38];
  46826. this.keysDown = [40];
  46827. this.keysLeft = [37];
  46828. this.keysRight = [39];
  46829. this.keysReset = [220];
  46830. this.panningSensibility = 50.0;
  46831. this.zoomingSensibility = 25.0;
  46832. this.useAltToZoom = true;
  46833. }
  46834. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46835. var _this = this;
  46836. if (this._onCanvasBlurObserver) {
  46837. return;
  46838. }
  46839. this._scene = this.camera.getScene();
  46840. this._engine = this._scene.getEngine();
  46841. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46842. _this._keys = [];
  46843. });
  46844. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46845. var evt = info.event;
  46846. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46847. _this._ctrlPressed = evt.ctrlKey;
  46848. _this._altPressed = evt.altKey;
  46849. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46850. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46851. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46852. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46853. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46854. var index = _this._keys.indexOf(evt.keyCode);
  46855. if (index === -1) {
  46856. _this._keys.push(evt.keyCode);
  46857. }
  46858. if (evt.preventDefault) {
  46859. if (!noPreventDefault) {
  46860. evt.preventDefault();
  46861. }
  46862. }
  46863. }
  46864. }
  46865. else {
  46866. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46867. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46868. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46869. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46870. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46871. var index = _this._keys.indexOf(evt.keyCode);
  46872. if (index >= 0) {
  46873. _this._keys.splice(index, 1);
  46874. }
  46875. if (evt.preventDefault) {
  46876. if (!noPreventDefault) {
  46877. evt.preventDefault();
  46878. }
  46879. }
  46880. }
  46881. }
  46882. });
  46883. };
  46884. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46885. if (this._scene) {
  46886. if (this._onKeyboardObserver) {
  46887. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46888. }
  46889. if (this._onCanvasBlurObserver) {
  46890. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46891. }
  46892. this._onKeyboardObserver = null;
  46893. this._onCanvasBlurObserver = null;
  46894. }
  46895. this._keys = [];
  46896. };
  46897. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46898. if (this._onKeyboardObserver) {
  46899. var camera = this.camera;
  46900. for (var index = 0; index < this._keys.length; index++) {
  46901. var keyCode = this._keys[index];
  46902. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46903. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46904. camera.inertialPanningX -= 1 / this.panningSensibility;
  46905. }
  46906. else {
  46907. camera.inertialAlphaOffset -= 0.01;
  46908. }
  46909. }
  46910. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46911. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46912. camera.inertialPanningY += 1 / this.panningSensibility;
  46913. }
  46914. else if (this._altPressed && this.useAltToZoom) {
  46915. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46916. }
  46917. else {
  46918. camera.inertialBetaOffset -= 0.01;
  46919. }
  46920. }
  46921. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46922. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46923. camera.inertialPanningX += 1 / this.panningSensibility;
  46924. }
  46925. else {
  46926. camera.inertialAlphaOffset += 0.01;
  46927. }
  46928. }
  46929. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46930. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46931. camera.inertialPanningY -= 1 / this.panningSensibility;
  46932. }
  46933. else if (this._altPressed && this.useAltToZoom) {
  46934. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  46935. }
  46936. else {
  46937. camera.inertialBetaOffset += 0.01;
  46938. }
  46939. }
  46940. else if (this.keysReset.indexOf(keyCode) !== -1) {
  46941. camera.restoreState();
  46942. }
  46943. }
  46944. }
  46945. };
  46946. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  46947. return "ArcRotateCameraKeyboardMoveInput";
  46948. };
  46949. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46950. return "keyboard";
  46951. };
  46952. __decorate([
  46953. BABYLON.serialize()
  46954. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46955. __decorate([
  46956. BABYLON.serialize()
  46957. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46958. __decorate([
  46959. BABYLON.serialize()
  46960. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46961. __decorate([
  46962. BABYLON.serialize()
  46963. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46964. __decorate([
  46965. BABYLON.serialize()
  46966. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  46967. __decorate([
  46968. BABYLON.serialize()
  46969. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  46970. __decorate([
  46971. BABYLON.serialize()
  46972. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  46973. __decorate([
  46974. BABYLON.serialize()
  46975. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  46976. return ArcRotateCameraKeyboardMoveInput;
  46977. }());
  46978. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  46979. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  46980. })(BABYLON || (BABYLON = {}));
  46981. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  46982. var BABYLON;
  46983. (function (BABYLON) {
  46984. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  46985. function ArcRotateCameraMouseWheelInput() {
  46986. this.wheelPrecision = 3.0;
  46987. /**
  46988. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  46989. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  46990. */
  46991. this.wheelDeltaPercentage = 0;
  46992. }
  46993. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  46994. var _this = this;
  46995. this._wheel = function (p, s) {
  46996. //sanity check - this should be a PointerWheel event.
  46997. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  46998. return;
  46999. var event = p.event;
  47000. var delta = 0;
  47001. if (event.wheelDelta) {
  47002. if (_this.wheelDeltaPercentage) {
  47003. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47004. if (event.wheelDelta > 0) {
  47005. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47006. }
  47007. else {
  47008. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47009. }
  47010. }
  47011. else {
  47012. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47013. }
  47014. }
  47015. else if (event.detail) {
  47016. delta = -event.detail / _this.wheelPrecision;
  47017. }
  47018. if (delta)
  47019. _this.camera.inertialRadiusOffset += delta;
  47020. if (event.preventDefault) {
  47021. if (!noPreventDefault) {
  47022. event.preventDefault();
  47023. }
  47024. }
  47025. };
  47026. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47027. };
  47028. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47029. if (this._observer && element) {
  47030. this.camera.getScene().onPointerObservable.remove(this._observer);
  47031. this._observer = null;
  47032. this._wheel = null;
  47033. }
  47034. };
  47035. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47036. return "ArcRotateCameraMouseWheelInput";
  47037. };
  47038. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47039. return "mousewheel";
  47040. };
  47041. __decorate([
  47042. BABYLON.serialize()
  47043. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47044. __decorate([
  47045. BABYLON.serialize()
  47046. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47047. return ArcRotateCameraMouseWheelInput;
  47048. }());
  47049. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47050. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47051. })(BABYLON || (BABYLON = {}));
  47052. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47053. var BABYLON;
  47054. (function (BABYLON) {
  47055. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47056. function ArcRotateCameraPointersInput() {
  47057. this.buttons = [0, 1, 2];
  47058. this.angularSensibilityX = 1000.0;
  47059. this.angularSensibilityY = 1000.0;
  47060. this.pinchPrecision = 12.0;
  47061. /**
  47062. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47063. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47064. */
  47065. this.pinchDeltaPercentage = 0;
  47066. this.panningSensibility = 1000.0;
  47067. this.multiTouchPanning = true;
  47068. this.multiTouchPanAndZoom = true;
  47069. this._isPanClick = false;
  47070. this.pinchInwards = true;
  47071. }
  47072. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47073. var _this = this;
  47074. var engine = this.camera.getEngine();
  47075. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47076. var pointA = null;
  47077. var pointB = null;
  47078. var previousPinchSquaredDistance = 0;
  47079. var initialDistance = 0;
  47080. var twoFingerActivityCount = 0;
  47081. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47082. this._pointerInput = function (p, s) {
  47083. var evt = p.event;
  47084. var isTouch = p.event.pointerType === "touch";
  47085. if (engine.isInVRExclusivePointerMode) {
  47086. return;
  47087. }
  47088. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47089. return;
  47090. }
  47091. var srcElement = (evt.srcElement || evt.target);
  47092. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47093. try {
  47094. srcElement.setPointerCapture(evt.pointerId);
  47095. }
  47096. catch (e) {
  47097. //Nothing to do with the error. Execution will continue.
  47098. }
  47099. // Manage panning with pan button click
  47100. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47101. // manage pointers
  47102. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47103. if (pointA === null) {
  47104. pointA = cacheSoloPointer;
  47105. }
  47106. else if (pointB === null) {
  47107. pointB = cacheSoloPointer;
  47108. }
  47109. if (!noPreventDefault) {
  47110. evt.preventDefault();
  47111. element.focus();
  47112. }
  47113. }
  47114. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47115. _this.camera.restoreState();
  47116. }
  47117. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47118. try {
  47119. srcElement.releasePointerCapture(evt.pointerId);
  47120. }
  47121. catch (e) {
  47122. //Nothing to do with the error.
  47123. }
  47124. cacheSoloPointer = null;
  47125. previousPinchSquaredDistance = 0;
  47126. previousMultiTouchPanPosition.isPaning = false;
  47127. previousMultiTouchPanPosition.isPinching = false;
  47128. twoFingerActivityCount = 0;
  47129. initialDistance = 0;
  47130. if (!isTouch) {
  47131. pointB = null; // Mouse and pen are mono pointer
  47132. }
  47133. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47134. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47135. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47136. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47137. if (engine._badOS) {
  47138. pointA = pointB = null;
  47139. }
  47140. else {
  47141. //only remove the impacted pointer in case of multitouch allowing on most
  47142. //platforms switching from rotate to zoom and pan seamlessly.
  47143. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47144. pointA = pointB;
  47145. pointB = null;
  47146. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47147. }
  47148. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47149. pointB = null;
  47150. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47151. }
  47152. else {
  47153. pointA = pointB = null;
  47154. }
  47155. }
  47156. if (!noPreventDefault) {
  47157. evt.preventDefault();
  47158. }
  47159. }
  47160. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47161. if (!noPreventDefault) {
  47162. evt.preventDefault();
  47163. }
  47164. // One button down
  47165. if (pointA && pointB === null && cacheSoloPointer) {
  47166. if (_this.panningSensibility !== 0 &&
  47167. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47168. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47169. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47170. }
  47171. else {
  47172. var offsetX = evt.clientX - cacheSoloPointer.x;
  47173. var offsetY = evt.clientY - cacheSoloPointer.y;
  47174. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47175. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47176. }
  47177. cacheSoloPointer.x = evt.clientX;
  47178. cacheSoloPointer.y = evt.clientY;
  47179. }
  47180. // Two buttons down: pinch/pan
  47181. else if (pointA && pointB) {
  47182. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47183. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47184. ed.x = evt.clientX;
  47185. ed.y = evt.clientY;
  47186. var direction = _this.pinchInwards ? 1 : -1;
  47187. var distX = pointA.x - pointB.x;
  47188. var distY = pointA.y - pointB.y;
  47189. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47190. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47191. if (previousPinchSquaredDistance === 0) {
  47192. initialDistance = pinchDistance;
  47193. previousPinchSquaredDistance = pinchSquaredDistance;
  47194. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47195. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47196. return;
  47197. }
  47198. if (_this.multiTouchPanAndZoom) {
  47199. if (_this.pinchDeltaPercentage) {
  47200. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47201. }
  47202. else {
  47203. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47204. (_this.pinchPrecision *
  47205. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47206. direction);
  47207. }
  47208. if (_this.panningSensibility !== 0) {
  47209. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47210. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47211. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47212. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47213. previousMultiTouchPanPosition.x = pointersCenterX;
  47214. previousMultiTouchPanPosition.y = pointersCenterY;
  47215. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47216. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47217. }
  47218. }
  47219. else {
  47220. twoFingerActivityCount++;
  47221. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47222. if (_this.pinchDeltaPercentage) {
  47223. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47224. }
  47225. else {
  47226. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47227. (_this.pinchPrecision *
  47228. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47229. direction);
  47230. }
  47231. previousMultiTouchPanPosition.isPaning = false;
  47232. previousMultiTouchPanPosition.isPinching = true;
  47233. }
  47234. else {
  47235. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47236. if (!previousMultiTouchPanPosition.isPaning) {
  47237. previousMultiTouchPanPosition.isPaning = true;
  47238. previousMultiTouchPanPosition.isPinching = false;
  47239. previousMultiTouchPanPosition.x = ed.x;
  47240. previousMultiTouchPanPosition.y = ed.y;
  47241. return;
  47242. }
  47243. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47244. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47245. }
  47246. }
  47247. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47248. previousMultiTouchPanPosition.x = ed.x;
  47249. previousMultiTouchPanPosition.y = ed.y;
  47250. }
  47251. }
  47252. previousPinchSquaredDistance = pinchSquaredDistance;
  47253. }
  47254. }
  47255. };
  47256. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47257. this._onContextMenu = function (evt) {
  47258. evt.preventDefault();
  47259. };
  47260. if (!this.camera._useCtrlForPanning) {
  47261. element.addEventListener("contextmenu", this._onContextMenu, false);
  47262. }
  47263. this._onLostFocus = function () {
  47264. //this._keys = [];
  47265. pointA = pointB = null;
  47266. previousPinchSquaredDistance = 0;
  47267. previousMultiTouchPanPosition.isPaning = false;
  47268. previousMultiTouchPanPosition.isPinching = false;
  47269. twoFingerActivityCount = 0;
  47270. cacheSoloPointer = null;
  47271. initialDistance = 0;
  47272. };
  47273. this._onMouseMove = function (evt) {
  47274. if (!engine.isPointerLock) {
  47275. return;
  47276. }
  47277. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47278. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47279. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47280. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47281. if (!noPreventDefault) {
  47282. evt.preventDefault();
  47283. }
  47284. };
  47285. this._onGestureStart = function (e) {
  47286. if (window.MSGesture === undefined) {
  47287. return;
  47288. }
  47289. if (!_this._MSGestureHandler) {
  47290. _this._MSGestureHandler = new MSGesture();
  47291. _this._MSGestureHandler.target = element;
  47292. }
  47293. _this._MSGestureHandler.addPointer(e.pointerId);
  47294. };
  47295. this._onGesture = function (e) {
  47296. _this.camera.radius *= e.scale;
  47297. if (e.preventDefault) {
  47298. if (!noPreventDefault) {
  47299. e.stopPropagation();
  47300. e.preventDefault();
  47301. }
  47302. }
  47303. };
  47304. element.addEventListener("mousemove", this._onMouseMove, false);
  47305. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47306. element.addEventListener("MSGestureChange", this._onGesture, false);
  47307. BABYLON.Tools.RegisterTopRootEvents([
  47308. { name: "blur", handler: this._onLostFocus }
  47309. ]);
  47310. };
  47311. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47312. if (this._onLostFocus) {
  47313. BABYLON.Tools.UnregisterTopRootEvents([
  47314. { name: "blur", handler: this._onLostFocus }
  47315. ]);
  47316. }
  47317. if (element && this._observer) {
  47318. this.camera.getScene().onPointerObservable.remove(this._observer);
  47319. this._observer = null;
  47320. if (this._onContextMenu) {
  47321. element.removeEventListener("contextmenu", this._onContextMenu);
  47322. }
  47323. if (this._onMouseMove) {
  47324. element.removeEventListener("mousemove", this._onMouseMove);
  47325. }
  47326. if (this._onGestureStart) {
  47327. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47328. }
  47329. if (this._onGesture) {
  47330. element.removeEventListener("MSGestureChange", this._onGesture);
  47331. }
  47332. this._isPanClick = false;
  47333. this.pinchInwards = true;
  47334. this._onMouseMove = null;
  47335. this._onGestureStart = null;
  47336. this._onGesture = null;
  47337. this._MSGestureHandler = null;
  47338. this._onLostFocus = null;
  47339. this._onContextMenu = null;
  47340. }
  47341. };
  47342. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47343. return "ArcRotateCameraPointersInput";
  47344. };
  47345. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47346. return "pointers";
  47347. };
  47348. __decorate([
  47349. BABYLON.serialize()
  47350. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47351. __decorate([
  47352. BABYLON.serialize()
  47353. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47354. __decorate([
  47355. BABYLON.serialize()
  47356. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47357. __decorate([
  47358. BABYLON.serialize()
  47359. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47360. __decorate([
  47361. BABYLON.serialize()
  47362. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47363. __decorate([
  47364. BABYLON.serialize()
  47365. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47366. __decorate([
  47367. BABYLON.serialize()
  47368. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47369. __decorate([
  47370. BABYLON.serialize()
  47371. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47372. return ArcRotateCameraPointersInput;
  47373. }());
  47374. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47375. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47376. })(BABYLON || (BABYLON = {}));
  47377. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47378. var BABYLON;
  47379. (function (BABYLON) {
  47380. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47381. __extends(ArcRotateCameraInputsManager, _super);
  47382. function ArcRotateCameraInputsManager(camera) {
  47383. return _super.call(this, camera) || this;
  47384. }
  47385. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47386. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47387. return this;
  47388. };
  47389. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47390. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47391. return this;
  47392. };
  47393. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47394. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47395. return this;
  47396. };
  47397. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  47398. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  47399. return this;
  47400. };
  47401. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47402. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47403. return this;
  47404. };
  47405. return ArcRotateCameraInputsManager;
  47406. }(BABYLON.CameraInputsManager));
  47407. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47408. })(BABYLON || (BABYLON = {}));
  47409. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47410. var BABYLON;
  47411. (function (BABYLON) {
  47412. var ArcRotateCamera = /** @class */ (function (_super) {
  47413. __extends(ArcRotateCamera, _super);
  47414. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47415. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47416. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47417. _this.inertialAlphaOffset = 0;
  47418. _this.inertialBetaOffset = 0;
  47419. _this.inertialRadiusOffset = 0;
  47420. _this.lowerAlphaLimit = null;
  47421. _this.upperAlphaLimit = null;
  47422. _this.lowerBetaLimit = 0.01;
  47423. _this.upperBetaLimit = Math.PI;
  47424. _this.lowerRadiusLimit = null;
  47425. _this.upperRadiusLimit = null;
  47426. _this.inertialPanningX = 0;
  47427. _this.inertialPanningY = 0;
  47428. _this.pinchToPanMaxDistance = 20;
  47429. _this.panningDistanceLimit = null;
  47430. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47431. _this.panningInertia = 0.9;
  47432. //-- end properties for backward compatibility for inputs
  47433. _this.zoomOnFactor = 1;
  47434. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47435. _this.allowUpsideDown = true;
  47436. _this._viewMatrix = new BABYLON.Matrix();
  47437. // Panning
  47438. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47439. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47440. _this.checkCollisions = false;
  47441. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47442. _this._previousPosition = BABYLON.Vector3.Zero();
  47443. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47444. _this._newPosition = BABYLON.Vector3.Zero();
  47445. _this._computationVector = BABYLON.Vector3.Zero();
  47446. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47447. if (collidedMesh === void 0) { collidedMesh = null; }
  47448. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47449. newPosition.multiplyInPlace(_this._collider._radius);
  47450. }
  47451. if (!collidedMesh) {
  47452. _this._previousPosition.copyFrom(_this.position);
  47453. }
  47454. else {
  47455. _this.setPosition(newPosition);
  47456. if (_this.onCollide) {
  47457. _this.onCollide(collidedMesh);
  47458. }
  47459. }
  47460. // Recompute because of constraints
  47461. var cosa = Math.cos(_this.alpha);
  47462. var sina = Math.sin(_this.alpha);
  47463. var cosb = Math.cos(_this.beta);
  47464. var sinb = Math.sin(_this.beta);
  47465. if (sinb === 0) {
  47466. sinb = 0.0001;
  47467. }
  47468. var target = _this._getTargetPosition();
  47469. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47470. target.addToRef(_this._computationVector, _this._newPosition);
  47471. _this.position.copyFrom(_this._newPosition);
  47472. var up = _this.upVector;
  47473. if (_this.allowUpsideDown && _this.beta < 0) {
  47474. up = up.clone();
  47475. up = up.negate();
  47476. }
  47477. _this._computeViewMatrix(_this.position, target, up);
  47478. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47479. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47480. _this._collisionTriggered = false;
  47481. };
  47482. _this._target = BABYLON.Vector3.Zero();
  47483. if (target) {
  47484. _this.setTarget(target);
  47485. }
  47486. _this.alpha = alpha;
  47487. _this.beta = beta;
  47488. _this.radius = radius;
  47489. _this.getViewMatrix();
  47490. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47491. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47492. return _this;
  47493. }
  47494. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47495. get: function () {
  47496. return this._target;
  47497. },
  47498. set: function (value) {
  47499. this.setTarget(value);
  47500. },
  47501. enumerable: true,
  47502. configurable: true
  47503. });
  47504. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47505. //-- begin properties for backward compatibility for inputs
  47506. get: function () {
  47507. var pointers = this.inputs.attached["pointers"];
  47508. if (pointers)
  47509. return pointers.angularSensibilityX;
  47510. return 0;
  47511. },
  47512. set: function (value) {
  47513. var pointers = this.inputs.attached["pointers"];
  47514. if (pointers) {
  47515. pointers.angularSensibilityX = value;
  47516. }
  47517. },
  47518. enumerable: true,
  47519. configurable: true
  47520. });
  47521. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47522. get: function () {
  47523. var pointers = this.inputs.attached["pointers"];
  47524. if (pointers)
  47525. return pointers.angularSensibilityY;
  47526. return 0;
  47527. },
  47528. set: function (value) {
  47529. var pointers = this.inputs.attached["pointers"];
  47530. if (pointers) {
  47531. pointers.angularSensibilityY = value;
  47532. }
  47533. },
  47534. enumerable: true,
  47535. configurable: true
  47536. });
  47537. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47538. get: function () {
  47539. var pointers = this.inputs.attached["pointers"];
  47540. if (pointers)
  47541. return pointers.pinchPrecision;
  47542. return 0;
  47543. },
  47544. set: function (value) {
  47545. var pointers = this.inputs.attached["pointers"];
  47546. if (pointers) {
  47547. pointers.pinchPrecision = value;
  47548. }
  47549. },
  47550. enumerable: true,
  47551. configurable: true
  47552. });
  47553. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47554. get: function () {
  47555. var pointers = this.inputs.attached["pointers"];
  47556. if (pointers)
  47557. return pointers.pinchDeltaPercentage;
  47558. return 0;
  47559. },
  47560. set: function (value) {
  47561. var pointers = this.inputs.attached["pointers"];
  47562. if (pointers) {
  47563. pointers.pinchDeltaPercentage = value;
  47564. }
  47565. },
  47566. enumerable: true,
  47567. configurable: true
  47568. });
  47569. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47570. get: function () {
  47571. var pointers = this.inputs.attached["pointers"];
  47572. if (pointers)
  47573. return pointers.panningSensibility;
  47574. return 0;
  47575. },
  47576. set: function (value) {
  47577. var pointers = this.inputs.attached["pointers"];
  47578. if (pointers) {
  47579. pointers.panningSensibility = value;
  47580. }
  47581. },
  47582. enumerable: true,
  47583. configurable: true
  47584. });
  47585. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47586. get: function () {
  47587. var keyboard = this.inputs.attached["keyboard"];
  47588. if (keyboard)
  47589. return keyboard.keysUp;
  47590. return [];
  47591. },
  47592. set: function (value) {
  47593. var keyboard = this.inputs.attached["keyboard"];
  47594. if (keyboard)
  47595. keyboard.keysUp = value;
  47596. },
  47597. enumerable: true,
  47598. configurable: true
  47599. });
  47600. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47601. get: function () {
  47602. var keyboard = this.inputs.attached["keyboard"];
  47603. if (keyboard)
  47604. return keyboard.keysDown;
  47605. return [];
  47606. },
  47607. set: function (value) {
  47608. var keyboard = this.inputs.attached["keyboard"];
  47609. if (keyboard)
  47610. keyboard.keysDown = value;
  47611. },
  47612. enumerable: true,
  47613. configurable: true
  47614. });
  47615. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47616. get: function () {
  47617. var keyboard = this.inputs.attached["keyboard"];
  47618. if (keyboard)
  47619. return keyboard.keysLeft;
  47620. return [];
  47621. },
  47622. set: function (value) {
  47623. var keyboard = this.inputs.attached["keyboard"];
  47624. if (keyboard)
  47625. keyboard.keysLeft = value;
  47626. },
  47627. enumerable: true,
  47628. configurable: true
  47629. });
  47630. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47631. get: function () {
  47632. var keyboard = this.inputs.attached["keyboard"];
  47633. if (keyboard)
  47634. return keyboard.keysRight;
  47635. return [];
  47636. },
  47637. set: function (value) {
  47638. var keyboard = this.inputs.attached["keyboard"];
  47639. if (keyboard)
  47640. keyboard.keysRight = value;
  47641. },
  47642. enumerable: true,
  47643. configurable: true
  47644. });
  47645. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47646. get: function () {
  47647. var mousewheel = this.inputs.attached["mousewheel"];
  47648. if (mousewheel)
  47649. return mousewheel.wheelPrecision;
  47650. return 0;
  47651. },
  47652. set: function (value) {
  47653. var mousewheel = this.inputs.attached["mousewheel"];
  47654. if (mousewheel)
  47655. mousewheel.wheelPrecision = value;
  47656. },
  47657. enumerable: true,
  47658. configurable: true
  47659. });
  47660. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47661. get: function () {
  47662. var mousewheel = this.inputs.attached["mousewheel"];
  47663. if (mousewheel)
  47664. return mousewheel.wheelDeltaPercentage;
  47665. return 0;
  47666. },
  47667. set: function (value) {
  47668. var mousewheel = this.inputs.attached["mousewheel"];
  47669. if (mousewheel)
  47670. mousewheel.wheelDeltaPercentage = value;
  47671. },
  47672. enumerable: true,
  47673. configurable: true
  47674. });
  47675. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47676. get: function () {
  47677. return this._bouncingBehavior;
  47678. },
  47679. enumerable: true,
  47680. configurable: true
  47681. });
  47682. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47683. get: function () {
  47684. return this._bouncingBehavior != null;
  47685. },
  47686. set: function (value) {
  47687. if (value === this.useBouncingBehavior) {
  47688. return;
  47689. }
  47690. if (value) {
  47691. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47692. this.addBehavior(this._bouncingBehavior);
  47693. }
  47694. else if (this._bouncingBehavior) {
  47695. this.removeBehavior(this._bouncingBehavior);
  47696. this._bouncingBehavior = null;
  47697. }
  47698. },
  47699. enumerable: true,
  47700. configurable: true
  47701. });
  47702. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47703. get: function () {
  47704. return this._framingBehavior;
  47705. },
  47706. enumerable: true,
  47707. configurable: true
  47708. });
  47709. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47710. get: function () {
  47711. return this._framingBehavior != null;
  47712. },
  47713. set: function (value) {
  47714. if (value === this.useFramingBehavior) {
  47715. return;
  47716. }
  47717. if (value) {
  47718. this._framingBehavior = new BABYLON.FramingBehavior();
  47719. this.addBehavior(this._framingBehavior);
  47720. }
  47721. else if (this._framingBehavior) {
  47722. this.removeBehavior(this._framingBehavior);
  47723. this._framingBehavior = null;
  47724. }
  47725. },
  47726. enumerable: true,
  47727. configurable: true
  47728. });
  47729. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47730. get: function () {
  47731. return this._autoRotationBehavior;
  47732. },
  47733. enumerable: true,
  47734. configurable: true
  47735. });
  47736. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47737. get: function () {
  47738. return this._autoRotationBehavior != null;
  47739. },
  47740. set: function (value) {
  47741. if (value === this.useAutoRotationBehavior) {
  47742. return;
  47743. }
  47744. if (value) {
  47745. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47746. this.addBehavior(this._autoRotationBehavior);
  47747. }
  47748. else if (this._autoRotationBehavior) {
  47749. this.removeBehavior(this._autoRotationBehavior);
  47750. this._autoRotationBehavior = null;
  47751. }
  47752. },
  47753. enumerable: true,
  47754. configurable: true
  47755. });
  47756. // Cache
  47757. ArcRotateCamera.prototype._initCache = function () {
  47758. _super.prototype._initCache.call(this);
  47759. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47760. this._cache.alpha = undefined;
  47761. this._cache.beta = undefined;
  47762. this._cache.radius = undefined;
  47763. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47764. };
  47765. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47766. if (!ignoreParentClass) {
  47767. _super.prototype._updateCache.call(this);
  47768. }
  47769. this._cache._target.copyFrom(this._getTargetPosition());
  47770. this._cache.alpha = this.alpha;
  47771. this._cache.beta = this.beta;
  47772. this._cache.radius = this.radius;
  47773. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47774. };
  47775. ArcRotateCamera.prototype._getTargetPosition = function () {
  47776. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47777. var pos = this._targetHost.getAbsolutePosition();
  47778. if (this._targetBoundingCenter) {
  47779. pos.addToRef(this._targetBoundingCenter, this._target);
  47780. }
  47781. else {
  47782. this._target.copyFrom(pos);
  47783. }
  47784. }
  47785. var lockedTargetPosition = this._getLockedTargetPosition();
  47786. if (lockedTargetPosition) {
  47787. return lockedTargetPosition;
  47788. }
  47789. return this._target;
  47790. };
  47791. ArcRotateCamera.prototype.storeState = function () {
  47792. this._storedAlpha = this.alpha;
  47793. this._storedBeta = this.beta;
  47794. this._storedRadius = this.radius;
  47795. this._storedTarget = this._getTargetPosition().clone();
  47796. return _super.prototype.storeState.call(this);
  47797. };
  47798. /**
  47799. * Restored camera state. You must call storeState() first
  47800. */
  47801. ArcRotateCamera.prototype._restoreStateValues = function () {
  47802. if (!_super.prototype._restoreStateValues.call(this)) {
  47803. return false;
  47804. }
  47805. this.alpha = this._storedAlpha;
  47806. this.beta = this._storedBeta;
  47807. this.radius = this._storedRadius;
  47808. this.setTarget(this._storedTarget.clone());
  47809. this.inertialAlphaOffset = 0;
  47810. this.inertialBetaOffset = 0;
  47811. this.inertialRadiusOffset = 0;
  47812. this.inertialPanningX = 0;
  47813. this.inertialPanningY = 0;
  47814. return true;
  47815. };
  47816. // Synchronized
  47817. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47818. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47819. return false;
  47820. return this._cache._target.equals(this._getTargetPosition())
  47821. && this._cache.alpha === this.alpha
  47822. && this._cache.beta === this.beta
  47823. && this._cache.radius === this.radius
  47824. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47825. };
  47826. // Methods
  47827. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47828. var _this = this;
  47829. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47830. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47831. this._useCtrlForPanning = useCtrlForPanning;
  47832. this._panningMouseButton = panningMouseButton;
  47833. this.inputs.attachElement(element, noPreventDefault);
  47834. this._reset = function () {
  47835. _this.inertialAlphaOffset = 0;
  47836. _this.inertialBetaOffset = 0;
  47837. _this.inertialRadiusOffset = 0;
  47838. _this.inertialPanningX = 0;
  47839. _this.inertialPanningY = 0;
  47840. };
  47841. };
  47842. ArcRotateCamera.prototype.detachControl = function (element) {
  47843. this.inputs.detachElement(element);
  47844. if (this._reset) {
  47845. this._reset();
  47846. }
  47847. };
  47848. ArcRotateCamera.prototype._checkInputs = function () {
  47849. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47850. if (this._collisionTriggered) {
  47851. return;
  47852. }
  47853. this.inputs.checkInputs();
  47854. // Inertia
  47855. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47856. var inertialAlphaOffset = this.inertialAlphaOffset;
  47857. if (this.beta <= 0)
  47858. inertialAlphaOffset *= -1;
  47859. if (this.getScene().useRightHandedSystem)
  47860. inertialAlphaOffset *= -1;
  47861. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47862. inertialAlphaOffset *= -1;
  47863. this.alpha += inertialAlphaOffset;
  47864. this.beta += this.inertialBetaOffset;
  47865. this.radius -= this.inertialRadiusOffset;
  47866. this.inertialAlphaOffset *= this.inertia;
  47867. this.inertialBetaOffset *= this.inertia;
  47868. this.inertialRadiusOffset *= this.inertia;
  47869. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47870. this.inertialAlphaOffset = 0;
  47871. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47872. this.inertialBetaOffset = 0;
  47873. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47874. this.inertialRadiusOffset = 0;
  47875. }
  47876. // Panning inertia
  47877. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47878. if (!this._localDirection) {
  47879. this._localDirection = BABYLON.Vector3.Zero();
  47880. this._transformedDirection = BABYLON.Vector3.Zero();
  47881. }
  47882. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47883. this._localDirection.multiplyInPlace(this.panningAxis);
  47884. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47885. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47886. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47887. if (!this.panningAxis.y) {
  47888. this._transformedDirection.y = 0;
  47889. }
  47890. if (!this._targetHost) {
  47891. if (this.panningDistanceLimit) {
  47892. this._transformedDirection.addInPlace(this._target);
  47893. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47894. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47895. this._target.copyFrom(this._transformedDirection);
  47896. }
  47897. }
  47898. else {
  47899. this._target.addInPlace(this._transformedDirection);
  47900. }
  47901. }
  47902. this.inertialPanningX *= this.panningInertia;
  47903. this.inertialPanningY *= this.panningInertia;
  47904. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47905. this.inertialPanningX = 0;
  47906. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47907. this.inertialPanningY = 0;
  47908. }
  47909. // Limits
  47910. this._checkLimits();
  47911. _super.prototype._checkInputs.call(this);
  47912. };
  47913. ArcRotateCamera.prototype._checkLimits = function () {
  47914. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  47915. if (this.allowUpsideDown && this.beta > Math.PI) {
  47916. this.beta = this.beta - (2 * Math.PI);
  47917. }
  47918. }
  47919. else {
  47920. if (this.beta < this.lowerBetaLimit) {
  47921. this.beta = this.lowerBetaLimit;
  47922. }
  47923. }
  47924. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  47925. if (this.allowUpsideDown && this.beta < -Math.PI) {
  47926. this.beta = this.beta + (2 * Math.PI);
  47927. }
  47928. }
  47929. else {
  47930. if (this.beta > this.upperBetaLimit) {
  47931. this.beta = this.upperBetaLimit;
  47932. }
  47933. }
  47934. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  47935. this.alpha = this.lowerAlphaLimit;
  47936. }
  47937. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  47938. this.alpha = this.upperAlphaLimit;
  47939. }
  47940. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  47941. this.radius = this.lowerRadiusLimit;
  47942. }
  47943. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  47944. this.radius = this.upperRadiusLimit;
  47945. }
  47946. };
  47947. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  47948. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  47949. this.radius = this._computationVector.length();
  47950. if (this.radius === 0) {
  47951. this.radius = 0.0001; // Just to avoid division by zero
  47952. }
  47953. // Alpha
  47954. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  47955. if (this._computationVector.z < 0) {
  47956. this.alpha = 2 * Math.PI - this.alpha;
  47957. }
  47958. // Beta
  47959. this.beta = Math.acos(this._computationVector.y / this.radius);
  47960. this._checkLimits();
  47961. };
  47962. ArcRotateCamera.prototype.setPosition = function (position) {
  47963. if (this.position.equals(position)) {
  47964. return;
  47965. }
  47966. this.position.copyFrom(position);
  47967. this.rebuildAnglesAndRadius();
  47968. };
  47969. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  47970. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  47971. if (allowSamePosition === void 0) { allowSamePosition = false; }
  47972. if (target.getBoundingInfo) {
  47973. if (toBoundingCenter) {
  47974. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  47975. }
  47976. else {
  47977. this._targetBoundingCenter = null;
  47978. }
  47979. this._targetHost = target;
  47980. this._target = this._getTargetPosition();
  47981. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  47982. }
  47983. else {
  47984. var newTarget = target;
  47985. var currentTarget = this._getTargetPosition();
  47986. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  47987. return;
  47988. }
  47989. this._targetHost = null;
  47990. this._target = newTarget;
  47991. this._targetBoundingCenter = null;
  47992. this.onMeshTargetChangedObservable.notifyObservers(null);
  47993. }
  47994. this.rebuildAnglesAndRadius();
  47995. };
  47996. ArcRotateCamera.prototype._getViewMatrix = function () {
  47997. // Compute
  47998. var cosa = Math.cos(this.alpha);
  47999. var sina = Math.sin(this.alpha);
  48000. var cosb = Math.cos(this.beta);
  48001. var sinb = Math.sin(this.beta);
  48002. if (sinb === 0) {
  48003. sinb = 0.0001;
  48004. }
  48005. var target = this._getTargetPosition();
  48006. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48007. target.addToRef(this._computationVector, this._newPosition);
  48008. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48009. if (!this._collider) {
  48010. this._collider = new BABYLON.Collider();
  48011. }
  48012. this._collider._radius = this.collisionRadius;
  48013. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48014. this._collisionTriggered = true;
  48015. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48016. }
  48017. else {
  48018. this.position.copyFrom(this._newPosition);
  48019. var up = this.upVector;
  48020. if (this.allowUpsideDown && sinb < 0) {
  48021. up = up.clone();
  48022. up = up.negate();
  48023. }
  48024. this._computeViewMatrix(this.position, target, up);
  48025. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48026. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48027. }
  48028. this._currentTarget = target;
  48029. return this._viewMatrix;
  48030. };
  48031. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48032. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48033. meshes = meshes || this.getScene().meshes;
  48034. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48035. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48036. this.radius = distance * this.zoomOnFactor;
  48037. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48038. };
  48039. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48040. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48041. var meshesOrMinMaxVector;
  48042. var distance;
  48043. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48044. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48045. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48046. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48047. }
  48048. else { //minMaxVector and distance
  48049. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48050. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48051. distance = minMaxVectorAndDistance.distance;
  48052. }
  48053. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48054. if (!doNotUpdateMaxZ) {
  48055. this.maxZ = distance * 2;
  48056. }
  48057. };
  48058. /**
  48059. * @override
  48060. * Override Camera.createRigCamera
  48061. */
  48062. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48063. var alphaShift = 0;
  48064. switch (this.cameraRigMode) {
  48065. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48066. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48067. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48068. case BABYLON.Camera.RIG_MODE_VR:
  48069. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48070. break;
  48071. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48072. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48073. break;
  48074. }
  48075. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48076. rigCam._cameraRigParams = {};
  48077. return rigCam;
  48078. };
  48079. /**
  48080. * @override
  48081. * Override Camera._updateRigCameras
  48082. */
  48083. ArcRotateCamera.prototype._updateRigCameras = function () {
  48084. var camLeft = this._rigCameras[0];
  48085. var camRight = this._rigCameras[1];
  48086. camLeft.beta = camRight.beta = this.beta;
  48087. camLeft.radius = camRight.radius = this.radius;
  48088. switch (this.cameraRigMode) {
  48089. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48090. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48091. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48092. case BABYLON.Camera.RIG_MODE_VR:
  48093. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48094. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48095. break;
  48096. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48097. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48098. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48099. break;
  48100. }
  48101. _super.prototype._updateRigCameras.call(this);
  48102. };
  48103. ArcRotateCamera.prototype.dispose = function () {
  48104. this.inputs.clear();
  48105. _super.prototype.dispose.call(this);
  48106. };
  48107. ArcRotateCamera.prototype.getClassName = function () {
  48108. return "ArcRotateCamera";
  48109. };
  48110. __decorate([
  48111. BABYLON.serialize()
  48112. ], ArcRotateCamera.prototype, "alpha", void 0);
  48113. __decorate([
  48114. BABYLON.serialize()
  48115. ], ArcRotateCamera.prototype, "beta", void 0);
  48116. __decorate([
  48117. BABYLON.serialize()
  48118. ], ArcRotateCamera.prototype, "radius", void 0);
  48119. __decorate([
  48120. BABYLON.serializeAsVector3("target")
  48121. ], ArcRotateCamera.prototype, "_target", void 0);
  48122. __decorate([
  48123. BABYLON.serialize()
  48124. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48125. __decorate([
  48126. BABYLON.serialize()
  48127. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48128. __decorate([
  48129. BABYLON.serialize()
  48130. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48131. __decorate([
  48132. BABYLON.serialize()
  48133. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48134. __decorate([
  48135. BABYLON.serialize()
  48136. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48137. __decorate([
  48138. BABYLON.serialize()
  48139. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48140. __decorate([
  48141. BABYLON.serialize()
  48142. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48143. __decorate([
  48144. BABYLON.serialize()
  48145. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48146. __decorate([
  48147. BABYLON.serialize()
  48148. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48149. __decorate([
  48150. BABYLON.serialize()
  48151. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48152. __decorate([
  48153. BABYLON.serialize()
  48154. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48155. __decorate([
  48156. BABYLON.serialize()
  48157. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48158. __decorate([
  48159. BABYLON.serialize()
  48160. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48161. __decorate([
  48162. BABYLON.serializeAsVector3()
  48163. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48164. __decorate([
  48165. BABYLON.serialize()
  48166. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48167. __decorate([
  48168. BABYLON.serialize()
  48169. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48170. __decorate([
  48171. BABYLON.serialize()
  48172. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48173. return ArcRotateCamera;
  48174. }(BABYLON.TargetCamera));
  48175. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48176. })(BABYLON || (BABYLON = {}));
  48177. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48178. var BABYLON;
  48179. (function (BABYLON) {
  48180. /**
  48181. * The HemisphericLight simulates the ambient environment light,
  48182. * so the passed direction is the light reflection direction, not the incoming direction.
  48183. */
  48184. var HemisphericLight = /** @class */ (function (_super) {
  48185. __extends(HemisphericLight, _super);
  48186. /**
  48187. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48188. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48189. * The HemisphericLight can't cast shadows.
  48190. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48191. * @param name The friendly name of the light
  48192. * @param direction The direction of the light reflection
  48193. * @param scene The scene the light belongs to
  48194. */
  48195. function HemisphericLight(name, direction, scene) {
  48196. var _this = _super.call(this, name, scene) || this;
  48197. /**
  48198. * The groundColor is the light in the opposite direction to the one specified during creation.
  48199. * 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.
  48200. */
  48201. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48202. _this.direction = direction || BABYLON.Vector3.Up();
  48203. return _this;
  48204. }
  48205. HemisphericLight.prototype._buildUniformLayout = function () {
  48206. this._uniformBuffer.addUniform("vLightData", 4);
  48207. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48208. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48209. this._uniformBuffer.addUniform("vLightGround", 3);
  48210. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48211. this._uniformBuffer.addUniform("depthValues", 2);
  48212. this._uniformBuffer.create();
  48213. };
  48214. /**
  48215. * Returns the string "HemisphericLight".
  48216. * @return The class name
  48217. */
  48218. HemisphericLight.prototype.getClassName = function () {
  48219. return "HemisphericLight";
  48220. };
  48221. /**
  48222. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48223. * Returns the updated direction.
  48224. * @param target The target the direction should point to
  48225. * @return The computed direction
  48226. */
  48227. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48228. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48229. return this.direction;
  48230. };
  48231. /**
  48232. * Returns the shadow generator associated to the light.
  48233. * @returns Always null for hemispheric lights because it does not support shadows.
  48234. */
  48235. HemisphericLight.prototype.getShadowGenerator = function () {
  48236. return null;
  48237. };
  48238. /**
  48239. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48240. * @param effect The effect to update
  48241. * @param lightIndex The index of the light in the effect to update
  48242. * @returns The hemispheric light
  48243. */
  48244. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48245. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48246. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48247. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48248. return this;
  48249. };
  48250. /**
  48251. * @hidden internal use only.
  48252. */
  48253. HemisphericLight.prototype._getWorldMatrix = function () {
  48254. if (!this._worldMatrix) {
  48255. this._worldMatrix = BABYLON.Matrix.Identity();
  48256. }
  48257. return this._worldMatrix;
  48258. };
  48259. /**
  48260. * Returns the integer 3.
  48261. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48262. */
  48263. HemisphericLight.prototype.getTypeID = function () {
  48264. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48265. };
  48266. __decorate([
  48267. BABYLON.serializeAsColor3()
  48268. ], HemisphericLight.prototype, "groundColor", void 0);
  48269. __decorate([
  48270. BABYLON.serializeAsVector3()
  48271. ], HemisphericLight.prototype, "direction", void 0);
  48272. return HemisphericLight;
  48273. }(BABYLON.Light));
  48274. BABYLON.HemisphericLight = HemisphericLight;
  48275. })(BABYLON || (BABYLON = {}));
  48276. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48277. var BABYLON;
  48278. (function (BABYLON) {
  48279. /**
  48280. * Base implementation IShadowLight
  48281. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48282. */
  48283. var ShadowLight = /** @class */ (function (_super) {
  48284. __extends(ShadowLight, _super);
  48285. function ShadowLight() {
  48286. var _this = _super !== null && _super.apply(this, arguments) || this;
  48287. _this._needProjectionMatrixCompute = true;
  48288. return _this;
  48289. }
  48290. ShadowLight.prototype._setPosition = function (value) {
  48291. this._position = value;
  48292. };
  48293. Object.defineProperty(ShadowLight.prototype, "position", {
  48294. /**
  48295. * Sets the position the shadow will be casted from. Also use as the light position for both
  48296. * point and spot lights.
  48297. */
  48298. get: function () {
  48299. return this._position;
  48300. },
  48301. /**
  48302. * Sets the position the shadow will be casted from. Also use as the light position for both
  48303. * point and spot lights.
  48304. */
  48305. set: function (value) {
  48306. this._setPosition(value);
  48307. },
  48308. enumerable: true,
  48309. configurable: true
  48310. });
  48311. ShadowLight.prototype._setDirection = function (value) {
  48312. this._direction = value;
  48313. };
  48314. Object.defineProperty(ShadowLight.prototype, "direction", {
  48315. /**
  48316. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48317. * Also use as the light direction on spot and directional lights.
  48318. */
  48319. get: function () {
  48320. return this._direction;
  48321. },
  48322. /**
  48323. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48324. * Also use as the light direction on spot and directional lights.
  48325. */
  48326. set: function (value) {
  48327. this._setDirection(value);
  48328. },
  48329. enumerable: true,
  48330. configurable: true
  48331. });
  48332. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48333. /**
  48334. * Gets the shadow projection clipping minimum z value.
  48335. */
  48336. get: function () {
  48337. return this._shadowMinZ;
  48338. },
  48339. /**
  48340. * Sets the shadow projection clipping minimum z value.
  48341. */
  48342. set: function (value) {
  48343. this._shadowMinZ = value;
  48344. this.forceProjectionMatrixCompute();
  48345. },
  48346. enumerable: true,
  48347. configurable: true
  48348. });
  48349. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48350. /**
  48351. * Sets the shadow projection clipping maximum z value.
  48352. */
  48353. get: function () {
  48354. return this._shadowMaxZ;
  48355. },
  48356. /**
  48357. * Gets the shadow projection clipping maximum z value.
  48358. */
  48359. set: function (value) {
  48360. this._shadowMaxZ = value;
  48361. this.forceProjectionMatrixCompute();
  48362. },
  48363. enumerable: true,
  48364. configurable: true
  48365. });
  48366. /**
  48367. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48368. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48369. */
  48370. ShadowLight.prototype.computeTransformedInformation = function () {
  48371. if (this.parent && this.parent.getWorldMatrix) {
  48372. if (!this.transformedPosition) {
  48373. this.transformedPosition = BABYLON.Vector3.Zero();
  48374. }
  48375. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48376. // In case the direction is present.
  48377. if (this.direction) {
  48378. if (!this.transformedDirection) {
  48379. this.transformedDirection = BABYLON.Vector3.Zero();
  48380. }
  48381. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48382. }
  48383. return true;
  48384. }
  48385. return false;
  48386. };
  48387. /**
  48388. * Return the depth scale used for the shadow map.
  48389. * @returns the depth scale.
  48390. */
  48391. ShadowLight.prototype.getDepthScale = function () {
  48392. return 50.0;
  48393. };
  48394. /**
  48395. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48396. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48397. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48398. */
  48399. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48400. return this.transformedDirection ? this.transformedDirection : this.direction;
  48401. };
  48402. /**
  48403. * Returns the ShadowLight absolute position in the World.
  48404. * @returns the position vector in world space
  48405. */
  48406. ShadowLight.prototype.getAbsolutePosition = function () {
  48407. return this.transformedPosition ? this.transformedPosition : this.position;
  48408. };
  48409. /**
  48410. * Sets the ShadowLight direction toward the passed target.
  48411. * @param target The point tot target in local space
  48412. * @returns the updated ShadowLight direction
  48413. */
  48414. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48415. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48416. return this.direction;
  48417. };
  48418. /**
  48419. * Returns the light rotation in euler definition.
  48420. * @returns the x y z rotation in local space.
  48421. */
  48422. ShadowLight.prototype.getRotation = function () {
  48423. this.direction.normalize();
  48424. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48425. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48426. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48427. };
  48428. /**
  48429. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48430. * @returns true if a cube texture needs to be use
  48431. */
  48432. ShadowLight.prototype.needCube = function () {
  48433. return false;
  48434. };
  48435. /**
  48436. * Detects if the projection matrix requires to be recomputed this frame.
  48437. * @returns true if it requires to be recomputed otherwise, false.
  48438. */
  48439. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48440. return this._needProjectionMatrixCompute;
  48441. };
  48442. /**
  48443. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48444. */
  48445. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48446. this._needProjectionMatrixCompute = true;
  48447. };
  48448. /**
  48449. * Get the world matrix of the sahdow lights.
  48450. * @hidden Internal Use Only
  48451. */
  48452. ShadowLight.prototype._getWorldMatrix = function () {
  48453. if (!this._worldMatrix) {
  48454. this._worldMatrix = BABYLON.Matrix.Identity();
  48455. }
  48456. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48457. return this._worldMatrix;
  48458. };
  48459. /**
  48460. * Gets the minZ used for shadow according to both the scene and the light.
  48461. * @param activeCamera The camera we are returning the min for
  48462. * @returns the depth min z
  48463. */
  48464. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48465. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48466. };
  48467. /**
  48468. * Gets the maxZ used for shadow according to both the scene and the light.
  48469. * @param activeCamera The camera we are returning the max for
  48470. * @returns the depth max z
  48471. */
  48472. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48473. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48474. };
  48475. /**
  48476. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48477. * @param matrix The materix to updated with the projection information
  48478. * @param viewMatrix The transform matrix of the light
  48479. * @param renderList The list of mesh to render in the map
  48480. * @returns The current light
  48481. */
  48482. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48483. if (this.customProjectionMatrixBuilder) {
  48484. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48485. }
  48486. else {
  48487. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48488. }
  48489. return this;
  48490. };
  48491. __decorate([
  48492. BABYLON.serializeAsVector3()
  48493. ], ShadowLight.prototype, "position", null);
  48494. __decorate([
  48495. BABYLON.serializeAsVector3()
  48496. ], ShadowLight.prototype, "direction", null);
  48497. __decorate([
  48498. BABYLON.serialize()
  48499. ], ShadowLight.prototype, "shadowMinZ", null);
  48500. __decorate([
  48501. BABYLON.serialize()
  48502. ], ShadowLight.prototype, "shadowMaxZ", null);
  48503. return ShadowLight;
  48504. }(BABYLON.Light));
  48505. BABYLON.ShadowLight = ShadowLight;
  48506. })(BABYLON || (BABYLON = {}));
  48507. //# sourceMappingURL=babylon.shadowLight.js.map
  48508. var BABYLON;
  48509. (function (BABYLON) {
  48510. /**
  48511. * A point light is a light defined by an unique point in world space.
  48512. * The light is emitted in every direction from this point.
  48513. * A good example of a point light is a standard light bulb.
  48514. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48515. */
  48516. var PointLight = /** @class */ (function (_super) {
  48517. __extends(PointLight, _super);
  48518. /**
  48519. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48520. * A PointLight emits the light in every direction.
  48521. * It can cast shadows.
  48522. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48523. * ```javascript
  48524. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48525. * ```
  48526. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48527. * @param name The light friendly name
  48528. * @param position The position of the point light in the scene
  48529. * @param scene The scene the lights belongs to
  48530. */
  48531. function PointLight(name, position, scene) {
  48532. var _this = _super.call(this, name, scene) || this;
  48533. _this._shadowAngle = Math.PI / 2;
  48534. _this.position = position;
  48535. return _this;
  48536. }
  48537. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48538. /**
  48539. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48540. * This specifies what angle the shadow will use to be created.
  48541. *
  48542. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48543. */
  48544. get: function () {
  48545. return this._shadowAngle;
  48546. },
  48547. /**
  48548. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48549. * This specifies what angle the shadow will use to be created.
  48550. *
  48551. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48552. */
  48553. set: function (value) {
  48554. this._shadowAngle = value;
  48555. this.forceProjectionMatrixCompute();
  48556. },
  48557. enumerable: true,
  48558. configurable: true
  48559. });
  48560. Object.defineProperty(PointLight.prototype, "direction", {
  48561. /**
  48562. * Gets the direction if it has been set.
  48563. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48564. */
  48565. get: function () {
  48566. return this._direction;
  48567. },
  48568. /**
  48569. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48570. */
  48571. set: function (value) {
  48572. var previousNeedCube = this.needCube();
  48573. this._direction = value;
  48574. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48575. this._shadowGenerator.recreateShadowMap();
  48576. }
  48577. },
  48578. enumerable: true,
  48579. configurable: true
  48580. });
  48581. /**
  48582. * Returns the string "PointLight"
  48583. * @returns the class name
  48584. */
  48585. PointLight.prototype.getClassName = function () {
  48586. return "PointLight";
  48587. };
  48588. /**
  48589. * Returns the integer 0.
  48590. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48591. */
  48592. PointLight.prototype.getTypeID = function () {
  48593. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48594. };
  48595. /**
  48596. * Specifies wether or not the shadowmap should be a cube texture.
  48597. * @returns true if the shadowmap needs to be a cube texture.
  48598. */
  48599. PointLight.prototype.needCube = function () {
  48600. return !this.direction;
  48601. };
  48602. /**
  48603. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48604. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48605. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48606. */
  48607. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48608. if (this.direction) {
  48609. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48610. }
  48611. else {
  48612. switch (faceIndex) {
  48613. case 0:
  48614. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48615. case 1:
  48616. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48617. case 2:
  48618. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48619. case 3:
  48620. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48621. case 4:
  48622. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48623. case 5:
  48624. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48625. }
  48626. }
  48627. return BABYLON.Vector3.Zero();
  48628. };
  48629. /**
  48630. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48631. * - fov = PI / 2
  48632. * - aspect ratio : 1.0
  48633. * - z-near and far equal to the active camera minZ and maxZ.
  48634. * Returns the PointLight.
  48635. */
  48636. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48637. var activeCamera = this.getScene().activeCamera;
  48638. if (!activeCamera) {
  48639. return;
  48640. }
  48641. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48642. };
  48643. PointLight.prototype._buildUniformLayout = function () {
  48644. this._uniformBuffer.addUniform("vLightData", 4);
  48645. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48646. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48647. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48648. this._uniformBuffer.addUniform("depthValues", 2);
  48649. this._uniformBuffer.create();
  48650. };
  48651. /**
  48652. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48653. * @param effect The effect to update
  48654. * @param lightIndex The index of the light in the effect to update
  48655. * @returns The point light
  48656. */
  48657. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48658. if (this.computeTransformedInformation()) {
  48659. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48660. return this;
  48661. }
  48662. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48663. return this;
  48664. };
  48665. __decorate([
  48666. BABYLON.serialize()
  48667. ], PointLight.prototype, "shadowAngle", null);
  48668. return PointLight;
  48669. }(BABYLON.ShadowLight));
  48670. BABYLON.PointLight = PointLight;
  48671. })(BABYLON || (BABYLON = {}));
  48672. //# sourceMappingURL=babylon.pointLight.js.map
  48673. var BABYLON;
  48674. (function (BABYLON) {
  48675. /**
  48676. * A directional light is defined by a direction (what a surprise!).
  48677. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48678. * 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.
  48679. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48680. */
  48681. var DirectionalLight = /** @class */ (function (_super) {
  48682. __extends(DirectionalLight, _super);
  48683. /**
  48684. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48685. * The directional light is emitted from everywhere in the given direction.
  48686. * It can cast shawdows.
  48687. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48688. * @param name The friendly name of the light
  48689. * @param direction The direction of the light
  48690. * @param scene The scene the light belongs to
  48691. */
  48692. function DirectionalLight(name, direction, scene) {
  48693. var _this = _super.call(this, name, scene) || this;
  48694. _this._shadowFrustumSize = 0;
  48695. _this._shadowOrthoScale = 0.1;
  48696. /**
  48697. * Automatically compute the projection matrix to best fit (including all the casters)
  48698. * on each frame.
  48699. */
  48700. _this.autoUpdateExtends = true;
  48701. // Cache
  48702. _this._orthoLeft = Number.MAX_VALUE;
  48703. _this._orthoRight = Number.MIN_VALUE;
  48704. _this._orthoTop = Number.MIN_VALUE;
  48705. _this._orthoBottom = Number.MAX_VALUE;
  48706. _this.position = direction.scale(-1.0);
  48707. _this.direction = direction;
  48708. return _this;
  48709. }
  48710. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48711. /**
  48712. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48713. */
  48714. get: function () {
  48715. return this._shadowFrustumSize;
  48716. },
  48717. /**
  48718. * Specifies a fix frustum size for the shadow generation.
  48719. */
  48720. set: function (value) {
  48721. this._shadowFrustumSize = value;
  48722. this.forceProjectionMatrixCompute();
  48723. },
  48724. enumerable: true,
  48725. configurable: true
  48726. });
  48727. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48728. /**
  48729. * Gets the shadow projection scale against the optimal computed one.
  48730. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48731. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48732. */
  48733. get: function () {
  48734. return this._shadowOrthoScale;
  48735. },
  48736. /**
  48737. * Sets the shadow projection scale against the optimal computed one.
  48738. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48739. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48740. */
  48741. set: function (value) {
  48742. this._shadowOrthoScale = value;
  48743. this.forceProjectionMatrixCompute();
  48744. },
  48745. enumerable: true,
  48746. configurable: true
  48747. });
  48748. /**
  48749. * Returns the string "DirectionalLight".
  48750. * @return The class name
  48751. */
  48752. DirectionalLight.prototype.getClassName = function () {
  48753. return "DirectionalLight";
  48754. };
  48755. /**
  48756. * Returns the integer 1.
  48757. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48758. */
  48759. DirectionalLight.prototype.getTypeID = function () {
  48760. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48761. };
  48762. /**
  48763. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48764. * Returns the DirectionalLight Shadow projection matrix.
  48765. */
  48766. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48767. if (this.shadowFrustumSize > 0) {
  48768. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48769. }
  48770. else {
  48771. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48772. }
  48773. };
  48774. /**
  48775. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48776. * Returns the DirectionalLight Shadow projection matrix.
  48777. */
  48778. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48779. var activeCamera = this.getScene().activeCamera;
  48780. if (!activeCamera) {
  48781. return;
  48782. }
  48783. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48784. };
  48785. /**
  48786. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48787. * Returns the DirectionalLight Shadow projection matrix.
  48788. */
  48789. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48790. var activeCamera = this.getScene().activeCamera;
  48791. if (!activeCamera) {
  48792. return;
  48793. }
  48794. // Check extends
  48795. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48796. var tempVector3 = BABYLON.Vector3.Zero();
  48797. this._orthoLeft = Number.MAX_VALUE;
  48798. this._orthoRight = Number.MIN_VALUE;
  48799. this._orthoTop = Number.MIN_VALUE;
  48800. this._orthoBottom = Number.MAX_VALUE;
  48801. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48802. var mesh = renderList[meshIndex];
  48803. if (!mesh) {
  48804. continue;
  48805. }
  48806. var boundingInfo = mesh.getBoundingInfo();
  48807. var boundingBox = boundingInfo.boundingBox;
  48808. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48809. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48810. if (tempVector3.x < this._orthoLeft)
  48811. this._orthoLeft = tempVector3.x;
  48812. if (tempVector3.y < this._orthoBottom)
  48813. this._orthoBottom = tempVector3.y;
  48814. if (tempVector3.x > this._orthoRight)
  48815. this._orthoRight = tempVector3.x;
  48816. if (tempVector3.y > this._orthoTop)
  48817. this._orthoTop = tempVector3.y;
  48818. }
  48819. }
  48820. }
  48821. var xOffset = this._orthoRight - this._orthoLeft;
  48822. var yOffset = this._orthoTop - this._orthoBottom;
  48823. 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);
  48824. };
  48825. DirectionalLight.prototype._buildUniformLayout = function () {
  48826. this._uniformBuffer.addUniform("vLightData", 4);
  48827. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48828. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48829. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48830. this._uniformBuffer.addUniform("depthValues", 2);
  48831. this._uniformBuffer.create();
  48832. };
  48833. /**
  48834. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48835. * @param effect The effect to update
  48836. * @param lightIndex The index of the light in the effect to update
  48837. * @returns The directional light
  48838. */
  48839. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48840. if (this.computeTransformedInformation()) {
  48841. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48842. return this;
  48843. }
  48844. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48845. return this;
  48846. };
  48847. /**
  48848. * Gets the minZ used for shadow according to both the scene and the light.
  48849. *
  48850. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48851. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48852. * @param activeCamera The camera we are returning the min for
  48853. * @returns the depth min z
  48854. */
  48855. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48856. return 1;
  48857. };
  48858. /**
  48859. * Gets the maxZ used for shadow according to both the scene and the light.
  48860. *
  48861. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48862. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48863. * @param activeCamera The camera we are returning the max for
  48864. * @returns the depth max z
  48865. */
  48866. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48867. return 1;
  48868. };
  48869. __decorate([
  48870. BABYLON.serialize()
  48871. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48872. __decorate([
  48873. BABYLON.serialize()
  48874. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48875. __decorate([
  48876. BABYLON.serialize()
  48877. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48878. return DirectionalLight;
  48879. }(BABYLON.ShadowLight));
  48880. BABYLON.DirectionalLight = DirectionalLight;
  48881. })(BABYLON || (BABYLON = {}));
  48882. //# sourceMappingURL=babylon.directionalLight.js.map
  48883. var BABYLON;
  48884. (function (BABYLON) {
  48885. /**
  48886. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48887. * These values define a cone of light starting from the position, emitting toward the direction.
  48888. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48889. * and the exponent defines the speed of the decay of the light with distance (reach).
  48890. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48891. */
  48892. var SpotLight = /** @class */ (function (_super) {
  48893. __extends(SpotLight, _super);
  48894. /**
  48895. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48896. * It can cast shadows.
  48897. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48898. * @param name The light friendly name
  48899. * @param position The position of the spot light in the scene
  48900. * @param direction The direction of the light in the scene
  48901. * @param angle The cone angle of the light in Radians
  48902. * @param exponent The light decay speed with the distance from the emission spot
  48903. * @param scene The scene the lights belongs to
  48904. */
  48905. function SpotLight(name, position, direction, angle, exponent, scene) {
  48906. var _this = _super.call(this, name, scene) || this;
  48907. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48908. _this._projectionTextureLightNear = 1e-6;
  48909. _this._projectionTextureLightFar = 1000.0;
  48910. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  48911. _this._projectionTextureViewLightDirty = true;
  48912. _this._projectionTextureProjectionLightDirty = true;
  48913. _this._projectionTextureDirty = true;
  48914. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  48915. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  48916. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  48917. _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);
  48918. _this.position = position;
  48919. _this.direction = direction;
  48920. _this.angle = angle;
  48921. _this.exponent = exponent;
  48922. return _this;
  48923. }
  48924. Object.defineProperty(SpotLight.prototype, "angle", {
  48925. /**
  48926. * Gets the cone angle of the spot light in Radians.
  48927. */
  48928. get: function () {
  48929. return this._angle;
  48930. },
  48931. /**
  48932. * Sets the cone angle of the spot light in Radians.
  48933. */
  48934. set: function (value) {
  48935. this._angle = value;
  48936. this._projectionTextureProjectionLightDirty = true;
  48937. this.forceProjectionMatrixCompute();
  48938. },
  48939. enumerable: true,
  48940. configurable: true
  48941. });
  48942. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  48943. /**
  48944. * Allows scaling the angle of the light for shadow generation only.
  48945. */
  48946. get: function () {
  48947. return this._shadowAngleScale;
  48948. },
  48949. /**
  48950. * Allows scaling the angle of the light for shadow generation only.
  48951. */
  48952. set: function (value) {
  48953. this._shadowAngleScale = value;
  48954. this.forceProjectionMatrixCompute();
  48955. },
  48956. enumerable: true,
  48957. configurable: true
  48958. });
  48959. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  48960. /**
  48961. * Allows reading the projecton texture
  48962. */
  48963. get: function () {
  48964. return this._projectionTextureMatrix;
  48965. },
  48966. enumerable: true,
  48967. configurable: true
  48968. });
  48969. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  48970. /**
  48971. * Gets the near clip of the Spotlight for texture projection.
  48972. */
  48973. get: function () {
  48974. return this._projectionTextureLightNear;
  48975. },
  48976. /**
  48977. * Sets the near clip of the Spotlight for texture projection.
  48978. */
  48979. set: function (value) {
  48980. this._projectionTextureLightNear = value;
  48981. this._projectionTextureProjectionLightDirty = true;
  48982. },
  48983. enumerable: true,
  48984. configurable: true
  48985. });
  48986. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  48987. /**
  48988. * Gets the far clip of the Spotlight for texture projection.
  48989. */
  48990. get: function () {
  48991. return this._projectionTextureLightFar;
  48992. },
  48993. /**
  48994. * Sets the far clip of the Spotlight for texture projection.
  48995. */
  48996. set: function (value) {
  48997. this._projectionTextureLightFar = value;
  48998. this._projectionTextureProjectionLightDirty = true;
  48999. },
  49000. enumerable: true,
  49001. configurable: true
  49002. });
  49003. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49004. /**
  49005. * Gets the Up vector of the Spotlight for texture projection.
  49006. */
  49007. get: function () {
  49008. return this._projectionTextureUpDirection;
  49009. },
  49010. /**
  49011. * Sets the Up vector of the Spotlight for texture projection.
  49012. */
  49013. set: function (value) {
  49014. this._projectionTextureUpDirection = value;
  49015. this._projectionTextureProjectionLightDirty = true;
  49016. },
  49017. enumerable: true,
  49018. configurable: true
  49019. });
  49020. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49021. /**
  49022. * Gets the projection texture of the light.
  49023. */
  49024. get: function () {
  49025. return this._projectionTexture;
  49026. },
  49027. /**
  49028. * Sets the projection texture of the light.
  49029. */
  49030. set: function (value) {
  49031. this._projectionTexture = value;
  49032. this._projectionTextureDirty = true;
  49033. },
  49034. enumerable: true,
  49035. configurable: true
  49036. });
  49037. /**
  49038. * Returns the string "SpotLight".
  49039. * @returns the class name
  49040. */
  49041. SpotLight.prototype.getClassName = function () {
  49042. return "SpotLight";
  49043. };
  49044. /**
  49045. * Returns the integer 2.
  49046. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49047. */
  49048. SpotLight.prototype.getTypeID = function () {
  49049. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49050. };
  49051. /**
  49052. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49053. */
  49054. SpotLight.prototype._setDirection = function (value) {
  49055. _super.prototype._setDirection.call(this, value);
  49056. this._projectionTextureViewLightDirty = true;
  49057. };
  49058. /**
  49059. * Overrides the position setter to recompute the projection texture view light Matrix.
  49060. */
  49061. SpotLight.prototype._setPosition = function (value) {
  49062. _super.prototype._setPosition.call(this, value);
  49063. this._projectionTextureViewLightDirty = true;
  49064. };
  49065. /**
  49066. * 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.
  49067. * Returns the SpotLight.
  49068. */
  49069. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49070. var activeCamera = this.getScene().activeCamera;
  49071. if (!activeCamera) {
  49072. return;
  49073. }
  49074. this._shadowAngleScale = this._shadowAngleScale || 1;
  49075. var angle = this._shadowAngleScale * this._angle;
  49076. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49077. };
  49078. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49079. this._projectionTextureViewLightDirty = false;
  49080. this._projectionTextureDirty = true;
  49081. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49082. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49083. };
  49084. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49085. this._projectionTextureProjectionLightDirty = false;
  49086. this._projectionTextureDirty = true;
  49087. var light_far = this.projectionTextureLightFar;
  49088. var light_near = this.projectionTextureLightNear;
  49089. var P = light_far / (light_far - light_near);
  49090. var Q = -P * light_near;
  49091. var S = 1.0 / Math.tan(this._angle / 2.0);
  49092. var A = 1.0;
  49093. 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);
  49094. };
  49095. /**
  49096. * Main function for light texture projection matrix computing.
  49097. */
  49098. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49099. this._projectionTextureDirty = false;
  49100. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49101. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49102. };
  49103. SpotLight.prototype._buildUniformLayout = function () {
  49104. this._uniformBuffer.addUniform("vLightData", 4);
  49105. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49106. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49107. this._uniformBuffer.addUniform("vLightDirection", 3);
  49108. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49109. this._uniformBuffer.addUniform("depthValues", 2);
  49110. this._uniformBuffer.create();
  49111. };
  49112. /**
  49113. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49114. * @param effect The effect to update
  49115. * @param lightIndex The index of the light in the effect to update
  49116. * @returns The spot light
  49117. */
  49118. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49119. var normalizeDirection;
  49120. if (this.computeTransformedInformation()) {
  49121. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49122. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49123. }
  49124. else {
  49125. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49126. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49127. }
  49128. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49129. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49130. if (this._projectionTextureViewLightDirty) {
  49131. this._computeProjectionTextureViewLightMatrix();
  49132. }
  49133. if (this._projectionTextureProjectionLightDirty) {
  49134. this._computeProjectionTextureProjectionLightMatrix();
  49135. }
  49136. if (this._projectionTextureDirty) {
  49137. this._computeProjectionTextureMatrix();
  49138. }
  49139. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49140. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49141. }
  49142. return this;
  49143. };
  49144. /**
  49145. * Disposes the light and the associated resources.
  49146. */
  49147. SpotLight.prototype.dispose = function () {
  49148. _super.prototype.dispose.call(this);
  49149. if (this._projectionTexture) {
  49150. this._projectionTexture.dispose();
  49151. }
  49152. };
  49153. __decorate([
  49154. BABYLON.serialize()
  49155. ], SpotLight.prototype, "angle", null);
  49156. __decorate([
  49157. BABYLON.serialize()
  49158. ], SpotLight.prototype, "shadowAngleScale", null);
  49159. __decorate([
  49160. BABYLON.serialize()
  49161. ], SpotLight.prototype, "exponent", void 0);
  49162. __decorate([
  49163. BABYLON.serialize()
  49164. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49165. __decorate([
  49166. BABYLON.serialize()
  49167. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49168. __decorate([
  49169. BABYLON.serialize()
  49170. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49171. __decorate([
  49172. BABYLON.serializeAsTexture("projectedLightTexture")
  49173. ], SpotLight.prototype, "_projectionTexture", void 0);
  49174. return SpotLight;
  49175. }(BABYLON.ShadowLight));
  49176. BABYLON.SpotLight = SpotLight;
  49177. })(BABYLON || (BABYLON = {}));
  49178. //# sourceMappingURL=babylon.spotLight.js.map
  49179. var BABYLON;
  49180. (function (BABYLON) {
  49181. /**
  49182. * Class used to override all child animations of a given target
  49183. */
  49184. var AnimationPropertiesOverride = /** @class */ (function () {
  49185. function AnimationPropertiesOverride() {
  49186. /**
  49187. * Gets or sets a value indicating if animation blending must be used
  49188. */
  49189. this.enableBlending = false;
  49190. /**
  49191. * Gets or sets the blending speed to use when enableBlending is true
  49192. */
  49193. this.blendingSpeed = 0.01;
  49194. /**
  49195. * Gets or sets the default loop mode to use
  49196. */
  49197. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49198. }
  49199. return AnimationPropertiesOverride;
  49200. }());
  49201. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49202. })(BABYLON || (BABYLON = {}));
  49203. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49204. var BABYLON;
  49205. (function (BABYLON) {
  49206. /**
  49207. * Represents the range of an animation
  49208. */
  49209. var AnimationRange = /** @class */ (function () {
  49210. /**
  49211. * Initializes the range of an animation
  49212. * @param name The name of the animation range
  49213. * @param from The starting frame of the animation
  49214. * @param to The ending frame of the animation
  49215. */
  49216. function AnimationRange(
  49217. /**The name of the animation range**/
  49218. name,
  49219. /**The starting frame of the animation */
  49220. from,
  49221. /**The ending frame of the animation*/
  49222. to) {
  49223. this.name = name;
  49224. this.from = from;
  49225. this.to = to;
  49226. }
  49227. /**
  49228. * Makes a copy of the animation range
  49229. * @returns A copy of the animation range
  49230. */
  49231. AnimationRange.prototype.clone = function () {
  49232. return new AnimationRange(this.name, this.from, this.to);
  49233. };
  49234. return AnimationRange;
  49235. }());
  49236. BABYLON.AnimationRange = AnimationRange;
  49237. /**
  49238. * Composed of a frame, and an action function
  49239. */
  49240. var AnimationEvent = /** @class */ (function () {
  49241. /**
  49242. * Initializes the animation event
  49243. * @param frame The frame for which the event is triggered
  49244. * @param action The event to perform when triggered
  49245. * @param onlyOnce Specifies if the event should be triggered only once
  49246. */
  49247. function AnimationEvent(
  49248. /** The frame for which the event is triggered **/
  49249. frame,
  49250. /** The event to perform when triggered **/
  49251. action,
  49252. /** Specifies if the event should be triggered only once**/
  49253. onlyOnce) {
  49254. this.frame = frame;
  49255. this.action = action;
  49256. this.onlyOnce = onlyOnce;
  49257. /**
  49258. * Specifies if the animation event is done
  49259. */
  49260. this.isDone = false;
  49261. }
  49262. /** @hidden */
  49263. AnimationEvent.prototype._clone = function () {
  49264. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49265. };
  49266. return AnimationEvent;
  49267. }());
  49268. BABYLON.AnimationEvent = AnimationEvent;
  49269. /**
  49270. * A cursor which tracks a point on a path
  49271. */
  49272. var PathCursor = /** @class */ (function () {
  49273. /**
  49274. * Initializes the path cursor
  49275. * @param path The path to track
  49276. */
  49277. function PathCursor(path) {
  49278. this.path = path;
  49279. /**
  49280. * Stores path cursor callbacks for when an onchange event is triggered
  49281. */
  49282. this._onchange = new Array();
  49283. /**
  49284. * The value of the path cursor
  49285. */
  49286. this.value = 0;
  49287. /**
  49288. * The animation array of the path cursor
  49289. */
  49290. this.animations = new Array();
  49291. }
  49292. /**
  49293. * Gets the cursor point on the path
  49294. * @returns A point on the path cursor at the cursor location
  49295. */
  49296. PathCursor.prototype.getPoint = function () {
  49297. var point = this.path.getPointAtLengthPosition(this.value);
  49298. return new BABYLON.Vector3(point.x, 0, point.y);
  49299. };
  49300. /**
  49301. * Moves the cursor ahead by the step amount
  49302. * @param step The amount to move the cursor forward
  49303. * @returns This path cursor
  49304. */
  49305. PathCursor.prototype.moveAhead = function (step) {
  49306. if (step === void 0) { step = 0.002; }
  49307. this.move(step);
  49308. return this;
  49309. };
  49310. /**
  49311. * Moves the cursor behind by the step amount
  49312. * @param step The amount to move the cursor back
  49313. * @returns This path cursor
  49314. */
  49315. PathCursor.prototype.moveBack = function (step) {
  49316. if (step === void 0) { step = 0.002; }
  49317. this.move(-step);
  49318. return this;
  49319. };
  49320. /**
  49321. * Moves the cursor by the step amount
  49322. * If the step amount is greater than one, an exception is thrown
  49323. * @param step The amount to move the cursor
  49324. * @returns This path cursor
  49325. */
  49326. PathCursor.prototype.move = function (step) {
  49327. if (Math.abs(step) > 1) {
  49328. throw "step size should be less than 1.";
  49329. }
  49330. this.value += step;
  49331. this.ensureLimits();
  49332. this.raiseOnChange();
  49333. return this;
  49334. };
  49335. /**
  49336. * Ensures that the value is limited between zero and one
  49337. * @returns This path cursor
  49338. */
  49339. PathCursor.prototype.ensureLimits = function () {
  49340. while (this.value > 1) {
  49341. this.value -= 1;
  49342. }
  49343. while (this.value < 0) {
  49344. this.value += 1;
  49345. }
  49346. return this;
  49347. };
  49348. /**
  49349. * Runs onchange callbacks on change (used by the animation engine)
  49350. * @returns This path cursor
  49351. */
  49352. PathCursor.prototype.raiseOnChange = function () {
  49353. var _this = this;
  49354. this._onchange.forEach(function (f) { return f(_this); });
  49355. return this;
  49356. };
  49357. /**
  49358. * Executes a function on change
  49359. * @param f A path cursor onchange callback
  49360. * @returns This path cursor
  49361. */
  49362. PathCursor.prototype.onchange = function (f) {
  49363. this._onchange.push(f);
  49364. return this;
  49365. };
  49366. return PathCursor;
  49367. }());
  49368. BABYLON.PathCursor = PathCursor;
  49369. /**
  49370. * Enum for the animation key frame interpolation type
  49371. */
  49372. var AnimationKeyInterpolation;
  49373. (function (AnimationKeyInterpolation) {
  49374. /**
  49375. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49376. */
  49377. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49378. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49379. /**
  49380. * Class used to store any kind of animation
  49381. */
  49382. var Animation = /** @class */ (function () {
  49383. /**
  49384. * Initializes the animation
  49385. * @param name Name of the animation
  49386. * @param targetProperty Property to animate
  49387. * @param framePerSecond The frames per second of the animation
  49388. * @param dataType The data type of the animation
  49389. * @param loopMode The loop mode of the animation
  49390. * @param enableBlendings Specifies if blending should be enabled
  49391. */
  49392. function Animation(
  49393. /**Name of the animation */
  49394. name,
  49395. /**Property to animate */
  49396. targetProperty,
  49397. /**The frames per second of the animation */
  49398. framePerSecond,
  49399. /**The data type of the animation */
  49400. dataType,
  49401. /**The loop mode of the animation */
  49402. loopMode,
  49403. /**Specifies if blending should be enabled */
  49404. enableBlending) {
  49405. this.name = name;
  49406. this.targetProperty = targetProperty;
  49407. this.framePerSecond = framePerSecond;
  49408. this.dataType = dataType;
  49409. this.loopMode = loopMode;
  49410. this.enableBlending = enableBlending;
  49411. /**
  49412. * @hidden Internal use only
  49413. */
  49414. this._runtimeAnimations = new Array();
  49415. /**
  49416. * The set of event that will be linked to this animation
  49417. */
  49418. this._events = new Array();
  49419. /**
  49420. * Stores the blending speed of the animation
  49421. */
  49422. this.blendingSpeed = 0.01;
  49423. /**
  49424. * Stores the animation ranges for the animation
  49425. */
  49426. this._ranges = {};
  49427. this.targetPropertyPath = targetProperty.split(".");
  49428. this.dataType = dataType;
  49429. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49430. }
  49431. /**
  49432. * @hidden Internal use
  49433. */
  49434. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49435. var dataType = undefined;
  49436. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49437. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49438. }
  49439. else if (from instanceof BABYLON.Quaternion) {
  49440. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49441. }
  49442. else if (from instanceof BABYLON.Vector3) {
  49443. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49444. }
  49445. else if (from instanceof BABYLON.Vector2) {
  49446. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49447. }
  49448. else if (from instanceof BABYLON.Color3) {
  49449. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49450. }
  49451. else if (from instanceof BABYLON.Size) {
  49452. dataType = Animation.ANIMATIONTYPE_SIZE;
  49453. }
  49454. if (dataType == undefined) {
  49455. return null;
  49456. }
  49457. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49458. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49459. animation.setKeys(keys);
  49460. if (easingFunction !== undefined) {
  49461. animation.setEasingFunction(easingFunction);
  49462. }
  49463. return animation;
  49464. };
  49465. /**
  49466. * Sets up an animation
  49467. * @param property The property to animate
  49468. * @param animationType The animation type to apply
  49469. * @param framePerSecond The frames per second of the animation
  49470. * @param easingFunction The easing function used in the animation
  49471. * @returns The created animation
  49472. */
  49473. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49474. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49475. animation.setEasingFunction(easingFunction);
  49476. return animation;
  49477. };
  49478. /**
  49479. * Create and start an animation on a node
  49480. * @param name defines the name of the global animation that will be run on all nodes
  49481. * @param node defines the root node where the animation will take place
  49482. * @param targetProperty defines property to animate
  49483. * @param framePerSecond defines the number of frame per second yo use
  49484. * @param totalFrame defines the number of frames in total
  49485. * @param from defines the initial value
  49486. * @param to defines the final value
  49487. * @param loopMode defines which loop mode you want to use (off by default)
  49488. * @param easingFunction defines the easing function to use (linear by default)
  49489. * @param onAnimationEnd defines the callback to call when animation end
  49490. * @returns the animatable created for this animation
  49491. */
  49492. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49493. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49494. if (!animation) {
  49495. return null;
  49496. }
  49497. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49498. };
  49499. /**
  49500. * Create and start an animation on a node and its descendants
  49501. * @param name defines the name of the global animation that will be run on all nodes
  49502. * @param node defines the root node where the animation will take place
  49503. * @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
  49504. * @param targetProperty defines property to animate
  49505. * @param framePerSecond defines the number of frame per second to use
  49506. * @param totalFrame defines the number of frames in total
  49507. * @param from defines the initial value
  49508. * @param to defines the final value
  49509. * @param loopMode defines which loop mode you want to use (off by default)
  49510. * @param easingFunction defines the easing function to use (linear by default)
  49511. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49512. * @returns the list of animatables created for all nodes
  49513. * @example https://www.babylonjs-playground.com/#MH0VLI
  49514. */
  49515. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49516. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49517. if (!animation) {
  49518. return null;
  49519. }
  49520. var scene = node.getScene();
  49521. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49522. };
  49523. /**
  49524. * Creates a new animation, merges it with the existing animations and starts it
  49525. * @param name Name of the animation
  49526. * @param node Node which contains the scene that begins the animations
  49527. * @param targetProperty Specifies which property to animate
  49528. * @param framePerSecond The frames per second of the animation
  49529. * @param totalFrame The total number of frames
  49530. * @param from The frame at the beginning of the animation
  49531. * @param to The frame at the end of the animation
  49532. * @param loopMode Specifies the loop mode of the animation
  49533. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49534. * @param onAnimationEnd Callback to run once the animation is complete
  49535. * @returns Nullable animation
  49536. */
  49537. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49538. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49539. if (!animation) {
  49540. return null;
  49541. }
  49542. node.animations.push(animation);
  49543. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49544. };
  49545. /**
  49546. * Transition property of an host to the target Value
  49547. * @param property The property to transition
  49548. * @param targetValue The target Value of the property
  49549. * @param host The object where the property to animate belongs
  49550. * @param scene Scene used to run the animation
  49551. * @param frameRate Framerate (in frame/s) to use
  49552. * @param transition The transition type we want to use
  49553. * @param duration The duration of the animation, in milliseconds
  49554. * @param onAnimationEnd Callback trigger at the end of the animation
  49555. * @returns Nullable animation
  49556. */
  49557. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49558. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49559. if (duration <= 0) {
  49560. host[property] = targetValue;
  49561. if (onAnimationEnd) {
  49562. onAnimationEnd();
  49563. }
  49564. return null;
  49565. }
  49566. var endFrame = frameRate * (duration / 1000);
  49567. transition.setKeys([{
  49568. frame: 0,
  49569. value: host[property].clone ? host[property].clone() : host[property]
  49570. },
  49571. {
  49572. frame: endFrame,
  49573. value: targetValue
  49574. }]);
  49575. if (!host.animations) {
  49576. host.animations = [];
  49577. }
  49578. host.animations.push(transition);
  49579. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49580. animation.onAnimationEnd = onAnimationEnd;
  49581. return animation;
  49582. };
  49583. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49584. /**
  49585. * Return the array of runtime animations currently using this animation
  49586. */
  49587. get: function () {
  49588. return this._runtimeAnimations;
  49589. },
  49590. enumerable: true,
  49591. configurable: true
  49592. });
  49593. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49594. /**
  49595. * Specifies if any of the runtime animations are currently running
  49596. */
  49597. get: function () {
  49598. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49599. var runtimeAnimation = _a[_i];
  49600. if (!runtimeAnimation.isStopped) {
  49601. return true;
  49602. }
  49603. }
  49604. return false;
  49605. },
  49606. enumerable: true,
  49607. configurable: true
  49608. });
  49609. // Methods
  49610. /**
  49611. * Converts the animation to a string
  49612. * @param fullDetails support for multiple levels of logging within scene loading
  49613. * @returns String form of the animation
  49614. */
  49615. Animation.prototype.toString = function (fullDetails) {
  49616. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49617. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49618. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49619. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49620. if (fullDetails) {
  49621. ret += ", Ranges: {";
  49622. var first = true;
  49623. for (var name in this._ranges) {
  49624. if (first) {
  49625. ret += ", ";
  49626. first = false;
  49627. }
  49628. ret += name;
  49629. }
  49630. ret += "}";
  49631. }
  49632. return ret;
  49633. };
  49634. /**
  49635. * Add an event to this animation
  49636. * @param event Event to add
  49637. */
  49638. Animation.prototype.addEvent = function (event) {
  49639. this._events.push(event);
  49640. };
  49641. /**
  49642. * Remove all events found at the given frame
  49643. * @param frame The frame to remove events from
  49644. */
  49645. Animation.prototype.removeEvents = function (frame) {
  49646. for (var index = 0; index < this._events.length; index++) {
  49647. if (this._events[index].frame === frame) {
  49648. this._events.splice(index, 1);
  49649. index--;
  49650. }
  49651. }
  49652. };
  49653. /**
  49654. * Retrieves all the events from the animation
  49655. * @returns Events from the animation
  49656. */
  49657. Animation.prototype.getEvents = function () {
  49658. return this._events;
  49659. };
  49660. /**
  49661. * Creates an animation range
  49662. * @param name Name of the animation range
  49663. * @param from Starting frame of the animation range
  49664. * @param to Ending frame of the animation
  49665. */
  49666. Animation.prototype.createRange = function (name, from, to) {
  49667. // check name not already in use; could happen for bones after serialized
  49668. if (!this._ranges[name]) {
  49669. this._ranges[name] = new AnimationRange(name, from, to);
  49670. }
  49671. };
  49672. /**
  49673. * Deletes an animation range by name
  49674. * @param name Name of the animation range to delete
  49675. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49676. */
  49677. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49678. if (deleteFrames === void 0) { deleteFrames = true; }
  49679. var range = this._ranges[name];
  49680. if (!range) {
  49681. return;
  49682. }
  49683. if (deleteFrames) {
  49684. var from = range.from;
  49685. var to = range.to;
  49686. // this loop MUST go high to low for multiple splices to work
  49687. for (var key = this._keys.length - 1; key >= 0; key--) {
  49688. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49689. this._keys.splice(key, 1);
  49690. }
  49691. }
  49692. }
  49693. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49694. };
  49695. /**
  49696. * Gets the animation range by name, or null if not defined
  49697. * @param name Name of the animation range
  49698. * @returns Nullable animation range
  49699. */
  49700. Animation.prototype.getRange = function (name) {
  49701. return this._ranges[name];
  49702. };
  49703. /**
  49704. * Gets the key frames from the animation
  49705. * @returns The key frames of the animation
  49706. */
  49707. Animation.prototype.getKeys = function () {
  49708. return this._keys;
  49709. };
  49710. /**
  49711. * Gets the highest frame rate of the animation
  49712. * @returns Highest frame rate of the animation
  49713. */
  49714. Animation.prototype.getHighestFrame = function () {
  49715. var ret = 0;
  49716. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49717. if (ret < this._keys[key].frame) {
  49718. ret = this._keys[key].frame;
  49719. }
  49720. }
  49721. return ret;
  49722. };
  49723. /**
  49724. * Gets the easing function of the animation
  49725. * @returns Easing function of the animation
  49726. */
  49727. Animation.prototype.getEasingFunction = function () {
  49728. return this._easingFunction;
  49729. };
  49730. /**
  49731. * Sets the easing function of the animation
  49732. * @param easingFunction A custom mathematical formula for animation
  49733. */
  49734. Animation.prototype.setEasingFunction = function (easingFunction) {
  49735. this._easingFunction = easingFunction;
  49736. };
  49737. /**
  49738. * Interpolates a scalar linearly
  49739. * @param startValue Start value of the animation curve
  49740. * @param endValue End value of the animation curve
  49741. * @param gradient Scalar amount to interpolate
  49742. * @returns Interpolated scalar value
  49743. */
  49744. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49745. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49746. };
  49747. /**
  49748. * Interpolates a scalar cubically
  49749. * @param startValue Start value of the animation curve
  49750. * @param outTangent End tangent of the animation
  49751. * @param endValue End value of the animation curve
  49752. * @param inTangent Start tangent of the animation curve
  49753. * @param gradient Scalar amount to interpolate
  49754. * @returns Interpolated scalar value
  49755. */
  49756. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49757. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49758. };
  49759. /**
  49760. * Interpolates a quaternion using a spherical linear interpolation
  49761. * @param startValue Start value of the animation curve
  49762. * @param endValue End value of the animation curve
  49763. * @param gradient Scalar amount to interpolate
  49764. * @returns Interpolated quaternion value
  49765. */
  49766. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49767. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49768. };
  49769. /**
  49770. * Interpolates a quaternion cubically
  49771. * @param startValue Start value of the animation curve
  49772. * @param outTangent End tangent of the animation curve
  49773. * @param endValue End value of the animation curve
  49774. * @param inTangent Start tangent of the animation curve
  49775. * @param gradient Scalar amount to interpolate
  49776. * @returns Interpolated quaternion value
  49777. */
  49778. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49779. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49780. };
  49781. /**
  49782. * Interpolates a Vector3 linearl
  49783. * @param startValue Start value of the animation curve
  49784. * @param endValue End value of the animation curve
  49785. * @param gradient Scalar amount to interpolate
  49786. * @returns Interpolated scalar value
  49787. */
  49788. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49789. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49790. };
  49791. /**
  49792. * Interpolates a Vector3 cubically
  49793. * @param startValue Start value of the animation curve
  49794. * @param outTangent End tangent of the animation
  49795. * @param endValue End value of the animation curve
  49796. * @param inTangent Start tangent of the animation curve
  49797. * @param gradient Scalar amount to interpolate
  49798. * @returns InterpolatedVector3 value
  49799. */
  49800. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49801. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49802. };
  49803. /**
  49804. * Interpolates a Vector2 linearly
  49805. * @param startValue Start value of the animation curve
  49806. * @param endValue End value of the animation curve
  49807. * @param gradient Scalar amount to interpolate
  49808. * @returns Interpolated Vector2 value
  49809. */
  49810. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49811. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49812. };
  49813. /**
  49814. * Interpolates a Vector2 cubically
  49815. * @param startValue Start value of the animation curve
  49816. * @param outTangent End tangent of the animation
  49817. * @param endValue End value of the animation curve
  49818. * @param inTangent Start tangent of the animation curve
  49819. * @param gradient Scalar amount to interpolate
  49820. * @returns Interpolated Vector2 value
  49821. */
  49822. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49823. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49824. };
  49825. /**
  49826. * Interpolates a size linearly
  49827. * @param startValue Start value of the animation curve
  49828. * @param endValue End value of the animation curve
  49829. * @param gradient Scalar amount to interpolate
  49830. * @returns Interpolated Size value
  49831. */
  49832. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49833. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49834. };
  49835. /**
  49836. * Interpolates a Color3 linearly
  49837. * @param startValue Start value of the animation curve
  49838. * @param endValue End value of the animation curve
  49839. * @param gradient Scalar amount to interpolate
  49840. * @returns Interpolated Color3 value
  49841. */
  49842. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49843. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49844. };
  49845. /**
  49846. * @hidden Internal use only
  49847. */
  49848. Animation.prototype._getKeyValue = function (value) {
  49849. if (typeof value === "function") {
  49850. return value();
  49851. }
  49852. return value;
  49853. };
  49854. /**
  49855. * @hidden Internal use only
  49856. */
  49857. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  49858. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49859. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49860. }
  49861. var keys = this.getKeys();
  49862. // Try to get a hash to find the right key
  49863. 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));
  49864. if (keys[startKeyIndex].frame >= currentFrame) {
  49865. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49866. startKeyIndex--;
  49867. }
  49868. }
  49869. for (var key = startKeyIndex; key < keys.length; key++) {
  49870. var endKey = keys[key + 1];
  49871. if (endKey.frame >= currentFrame) {
  49872. var startKey = keys[key];
  49873. var startValue = this._getKeyValue(startKey.value);
  49874. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  49875. return startValue;
  49876. }
  49877. var endValue = this._getKeyValue(endKey.value);
  49878. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  49879. var frameDelta = endKey.frame - startKey.frame;
  49880. // gradient : percent of currentFrame between the frame inf and the frame sup
  49881. var gradient = (currentFrame - startKey.frame) / frameDelta;
  49882. // check for easingFunction and correction of gradient
  49883. var easingFunction = this.getEasingFunction();
  49884. if (easingFunction != null) {
  49885. gradient = easingFunction.ease(gradient);
  49886. }
  49887. switch (this.dataType) {
  49888. // Float
  49889. case Animation.ANIMATIONTYPE_FLOAT:
  49890. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  49891. switch (loopMode) {
  49892. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49893. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49894. return floatValue;
  49895. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49896. return offsetValue * repeatCount + floatValue;
  49897. }
  49898. break;
  49899. // Quaternion
  49900. case Animation.ANIMATIONTYPE_QUATERNION:
  49901. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  49902. switch (loopMode) {
  49903. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49904. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49905. return quatValue;
  49906. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49907. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  49908. }
  49909. return quatValue;
  49910. // Vector3
  49911. case Animation.ANIMATIONTYPE_VECTOR3:
  49912. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  49913. switch (loopMode) {
  49914. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49915. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49916. return vec3Value;
  49917. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49918. return vec3Value.add(offsetValue.scale(repeatCount));
  49919. }
  49920. // Vector2
  49921. case Animation.ANIMATIONTYPE_VECTOR2:
  49922. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  49923. switch (loopMode) {
  49924. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49925. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49926. return vec2Value;
  49927. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49928. return vec2Value.add(offsetValue.scale(repeatCount));
  49929. }
  49930. // Size
  49931. case Animation.ANIMATIONTYPE_SIZE:
  49932. switch (loopMode) {
  49933. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49934. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49935. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  49936. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49937. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49938. }
  49939. // Color3
  49940. case Animation.ANIMATIONTYPE_COLOR3:
  49941. switch (loopMode) {
  49942. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49943. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49944. return this.color3InterpolateFunction(startValue, endValue, gradient);
  49945. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49946. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49947. }
  49948. // Matrix
  49949. case Animation.ANIMATIONTYPE_MATRIX:
  49950. switch (loopMode) {
  49951. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49952. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49953. if (Animation.AllowMatricesInterpolation) {
  49954. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  49955. }
  49956. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49957. return startValue;
  49958. }
  49959. default:
  49960. break;
  49961. }
  49962. break;
  49963. }
  49964. }
  49965. return this._getKeyValue(keys[keys.length - 1].value);
  49966. };
  49967. /**
  49968. * Defines the function to use to interpolate matrices
  49969. * @param startValue defines the start matrix
  49970. * @param endValue defines the end matrix
  49971. * @param gradient defines the gradient between both matrices
  49972. * @param result defines an optional target matrix where to store the interpolation
  49973. * @returns the interpolated matrix
  49974. */
  49975. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  49976. if (Animation.AllowMatrixDecomposeForInterpolation) {
  49977. if (result) {
  49978. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  49979. return result;
  49980. }
  49981. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  49982. }
  49983. if (result) {
  49984. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  49985. return result;
  49986. }
  49987. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  49988. };
  49989. /**
  49990. * Makes a copy of the animation
  49991. * @returns Cloned animation
  49992. */
  49993. Animation.prototype.clone = function () {
  49994. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  49995. clone.enableBlending = this.enableBlending;
  49996. clone.blendingSpeed = this.blendingSpeed;
  49997. if (this._keys) {
  49998. clone.setKeys(this._keys);
  49999. }
  50000. if (this._ranges) {
  50001. clone._ranges = {};
  50002. for (var name in this._ranges) {
  50003. var range = this._ranges[name];
  50004. if (!range) {
  50005. continue;
  50006. }
  50007. clone._ranges[name] = range.clone();
  50008. }
  50009. }
  50010. return clone;
  50011. };
  50012. /**
  50013. * Sets the key frames of the animation
  50014. * @param values The animation key frames to set
  50015. */
  50016. Animation.prototype.setKeys = function (values) {
  50017. this._keys = values.slice(0);
  50018. };
  50019. /**
  50020. * Serializes the animation to an object
  50021. * @returns Serialized object
  50022. */
  50023. Animation.prototype.serialize = function () {
  50024. var serializationObject = {};
  50025. serializationObject.name = this.name;
  50026. serializationObject.property = this.targetProperty;
  50027. serializationObject.framePerSecond = this.framePerSecond;
  50028. serializationObject.dataType = this.dataType;
  50029. serializationObject.loopBehavior = this.loopMode;
  50030. serializationObject.enableBlending = this.enableBlending;
  50031. serializationObject.blendingSpeed = this.blendingSpeed;
  50032. var dataType = this.dataType;
  50033. serializationObject.keys = [];
  50034. var keys = this.getKeys();
  50035. for (var index = 0; index < keys.length; index++) {
  50036. var animationKey = keys[index];
  50037. var key = {};
  50038. key.frame = animationKey.frame;
  50039. switch (dataType) {
  50040. case Animation.ANIMATIONTYPE_FLOAT:
  50041. key.values = [animationKey.value];
  50042. break;
  50043. case Animation.ANIMATIONTYPE_QUATERNION:
  50044. case Animation.ANIMATIONTYPE_MATRIX:
  50045. case Animation.ANIMATIONTYPE_VECTOR3:
  50046. case Animation.ANIMATIONTYPE_COLOR3:
  50047. key.values = animationKey.value.asArray();
  50048. break;
  50049. }
  50050. serializationObject.keys.push(key);
  50051. }
  50052. serializationObject.ranges = [];
  50053. for (var name in this._ranges) {
  50054. var source = this._ranges[name];
  50055. if (!source) {
  50056. continue;
  50057. }
  50058. var range = {};
  50059. range.name = name;
  50060. range.from = source.from;
  50061. range.to = source.to;
  50062. serializationObject.ranges.push(range);
  50063. }
  50064. return serializationObject;
  50065. };
  50066. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50067. /**
  50068. * Get the float animation type
  50069. */
  50070. get: function () {
  50071. return Animation._ANIMATIONTYPE_FLOAT;
  50072. },
  50073. enumerable: true,
  50074. configurable: true
  50075. });
  50076. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50077. /**
  50078. * Get the Vector3 animation type
  50079. */
  50080. get: function () {
  50081. return Animation._ANIMATIONTYPE_VECTOR3;
  50082. },
  50083. enumerable: true,
  50084. configurable: true
  50085. });
  50086. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50087. /**
  50088. * Get the Vectpr2 animation type
  50089. */
  50090. get: function () {
  50091. return Animation._ANIMATIONTYPE_VECTOR2;
  50092. },
  50093. enumerable: true,
  50094. configurable: true
  50095. });
  50096. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50097. /**
  50098. * Get the Size animation type
  50099. */
  50100. get: function () {
  50101. return Animation._ANIMATIONTYPE_SIZE;
  50102. },
  50103. enumerable: true,
  50104. configurable: true
  50105. });
  50106. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50107. /**
  50108. * Get the Quaternion animation type
  50109. */
  50110. get: function () {
  50111. return Animation._ANIMATIONTYPE_QUATERNION;
  50112. },
  50113. enumerable: true,
  50114. configurable: true
  50115. });
  50116. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50117. /**
  50118. * Get the Matrix animation type
  50119. */
  50120. get: function () {
  50121. return Animation._ANIMATIONTYPE_MATRIX;
  50122. },
  50123. enumerable: true,
  50124. configurable: true
  50125. });
  50126. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50127. /**
  50128. * Get the Color3 animation type
  50129. */
  50130. get: function () {
  50131. return Animation._ANIMATIONTYPE_COLOR3;
  50132. },
  50133. enumerable: true,
  50134. configurable: true
  50135. });
  50136. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50137. /**
  50138. * Get the Relative Loop Mode
  50139. */
  50140. get: function () {
  50141. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50142. },
  50143. enumerable: true,
  50144. configurable: true
  50145. });
  50146. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50147. /**
  50148. * Get the Cycle Loop Mode
  50149. */
  50150. get: function () {
  50151. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50152. },
  50153. enumerable: true,
  50154. configurable: true
  50155. });
  50156. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50157. /**
  50158. * Get the Constant Loop Mode
  50159. */
  50160. get: function () {
  50161. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50162. },
  50163. enumerable: true,
  50164. configurable: true
  50165. });
  50166. /** @hidden */
  50167. Animation._UniversalLerp = function (left, right, amount) {
  50168. var constructor = left.constructor;
  50169. if (constructor.Lerp) { // Lerp supported
  50170. return constructor.Lerp(left, right, amount);
  50171. }
  50172. else if (constructor.Slerp) { // Slerp supported
  50173. return constructor.Slerp(left, right, amount);
  50174. }
  50175. else if (left.toFixed) { // Number
  50176. return left * (1.0 - amount) + amount * right;
  50177. }
  50178. else { // Blending not supported
  50179. return right;
  50180. }
  50181. };
  50182. /**
  50183. * Parses an animation object and creates an animation
  50184. * @param parsedAnimation Parsed animation object
  50185. * @returns Animation object
  50186. */
  50187. Animation.Parse = function (parsedAnimation) {
  50188. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50189. var dataType = parsedAnimation.dataType;
  50190. var keys = [];
  50191. var data;
  50192. var index;
  50193. if (parsedAnimation.enableBlending) {
  50194. animation.enableBlending = parsedAnimation.enableBlending;
  50195. }
  50196. if (parsedAnimation.blendingSpeed) {
  50197. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50198. }
  50199. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50200. var key = parsedAnimation.keys[index];
  50201. var inTangent;
  50202. var outTangent;
  50203. switch (dataType) {
  50204. case Animation.ANIMATIONTYPE_FLOAT:
  50205. data = key.values[0];
  50206. if (key.values.length >= 1) {
  50207. inTangent = key.values[1];
  50208. }
  50209. if (key.values.length >= 2) {
  50210. outTangent = key.values[2];
  50211. }
  50212. break;
  50213. case Animation.ANIMATIONTYPE_QUATERNION:
  50214. data = BABYLON.Quaternion.FromArray(key.values);
  50215. if (key.values.length >= 8) {
  50216. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50217. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50218. inTangent = _inTangent;
  50219. }
  50220. }
  50221. if (key.values.length >= 12) {
  50222. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50223. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50224. outTangent = _outTangent;
  50225. }
  50226. }
  50227. break;
  50228. case Animation.ANIMATIONTYPE_MATRIX:
  50229. data = BABYLON.Matrix.FromArray(key.values);
  50230. break;
  50231. case Animation.ANIMATIONTYPE_COLOR3:
  50232. data = BABYLON.Color3.FromArray(key.values);
  50233. break;
  50234. case Animation.ANIMATIONTYPE_VECTOR3:
  50235. default:
  50236. data = BABYLON.Vector3.FromArray(key.values);
  50237. break;
  50238. }
  50239. var keyData = {};
  50240. keyData.frame = key.frame;
  50241. keyData.value = data;
  50242. if (inTangent != undefined) {
  50243. keyData.inTangent = inTangent;
  50244. }
  50245. if (outTangent != undefined) {
  50246. keyData.outTangent = outTangent;
  50247. }
  50248. keys.push(keyData);
  50249. }
  50250. animation.setKeys(keys);
  50251. if (parsedAnimation.ranges) {
  50252. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50253. data = parsedAnimation.ranges[index];
  50254. animation.createRange(data.name, data.from, data.to);
  50255. }
  50256. }
  50257. return animation;
  50258. };
  50259. /**
  50260. * Appends the serialized animations from the source animations
  50261. * @param source Source containing the animations
  50262. * @param destination Target to store the animations
  50263. */
  50264. Animation.AppendSerializedAnimations = function (source, destination) {
  50265. if (source.animations) {
  50266. destination.animations = [];
  50267. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50268. var animation = source.animations[animationIndex];
  50269. destination.animations.push(animation.serialize());
  50270. }
  50271. }
  50272. };
  50273. /**
  50274. * Use matrix interpolation instead of using direct key value when animating matrices
  50275. */
  50276. Animation.AllowMatricesInterpolation = false;
  50277. /**
  50278. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50279. */
  50280. Animation.AllowMatrixDecomposeForInterpolation = true;
  50281. // Statics
  50282. /**
  50283. * Float animation type
  50284. */
  50285. Animation._ANIMATIONTYPE_FLOAT = 0;
  50286. /**
  50287. * Vector3 animation type
  50288. */
  50289. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50290. /**
  50291. * Quaternion animation type
  50292. */
  50293. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50294. /**
  50295. * Matrix animation type
  50296. */
  50297. Animation._ANIMATIONTYPE_MATRIX = 3;
  50298. /**
  50299. * Color3 animation type
  50300. */
  50301. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50302. /**
  50303. * Vector2 animation type
  50304. */
  50305. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50306. /**
  50307. * Size animation type
  50308. */
  50309. Animation._ANIMATIONTYPE_SIZE = 6;
  50310. /**
  50311. * Relative Loop Mode
  50312. */
  50313. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50314. /**
  50315. * Cycle Loop Mode
  50316. */
  50317. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50318. /**
  50319. * Constant Loop Mode
  50320. */
  50321. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50322. return Animation;
  50323. }());
  50324. BABYLON.Animation = Animation;
  50325. })(BABYLON || (BABYLON = {}));
  50326. //# sourceMappingURL=babylon.animation.js.map
  50327. var BABYLON;
  50328. (function (BABYLON) {
  50329. /**
  50330. * This class defines the direct association between an animation and a target
  50331. */
  50332. var TargetedAnimation = /** @class */ (function () {
  50333. function TargetedAnimation() {
  50334. }
  50335. return TargetedAnimation;
  50336. }());
  50337. BABYLON.TargetedAnimation = TargetedAnimation;
  50338. /**
  50339. * Use this class to create coordinated animations on multiple targets
  50340. */
  50341. var AnimationGroup = /** @class */ (function () {
  50342. function AnimationGroup(name, scene) {
  50343. if (scene === void 0) { scene = null; }
  50344. this.name = name;
  50345. this._targetedAnimations = new Array();
  50346. this._animatables = new Array();
  50347. this._from = Number.MAX_VALUE;
  50348. this._to = -Number.MAX_VALUE;
  50349. this._speedRatio = 1;
  50350. this.onAnimationEndObservable = new BABYLON.Observable();
  50351. /**
  50352. * This observable will notify when all animations have ended.
  50353. */
  50354. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50355. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50356. this._scene.animationGroups.push(this);
  50357. }
  50358. Object.defineProperty(AnimationGroup.prototype, "from", {
  50359. /**
  50360. * Gets the first frame
  50361. */
  50362. get: function () {
  50363. return this._from;
  50364. },
  50365. enumerable: true,
  50366. configurable: true
  50367. });
  50368. Object.defineProperty(AnimationGroup.prototype, "to", {
  50369. /**
  50370. * Gets the last frame
  50371. */
  50372. get: function () {
  50373. return this._to;
  50374. },
  50375. enumerable: true,
  50376. configurable: true
  50377. });
  50378. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50379. /**
  50380. * Define if the animations are started
  50381. */
  50382. get: function () {
  50383. return this._isStarted;
  50384. },
  50385. enumerable: true,
  50386. configurable: true
  50387. });
  50388. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50389. /**
  50390. * Gets or sets the speed ratio to use for all animations
  50391. */
  50392. get: function () {
  50393. return this._speedRatio;
  50394. },
  50395. /**
  50396. * Gets or sets the speed ratio to use for all animations
  50397. */
  50398. set: function (value) {
  50399. if (this._speedRatio === value) {
  50400. return;
  50401. }
  50402. this._speedRatio = value;
  50403. for (var index = 0; index < this._animatables.length; index++) {
  50404. var animatable = this._animatables[index];
  50405. animatable.speedRatio = this._speedRatio;
  50406. }
  50407. },
  50408. enumerable: true,
  50409. configurable: true
  50410. });
  50411. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50412. /**
  50413. * Gets the targeted animations for this animation group
  50414. */
  50415. get: function () {
  50416. return this._targetedAnimations;
  50417. },
  50418. enumerable: true,
  50419. configurable: true
  50420. });
  50421. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50422. /**
  50423. * returning the list of animatables controlled by this animation group.
  50424. */
  50425. get: function () {
  50426. return this._animatables;
  50427. },
  50428. enumerable: true,
  50429. configurable: true
  50430. });
  50431. /**
  50432. * Add an animation (with its target) in the group
  50433. * @param animation defines the animation we want to add
  50434. * @param target defines the target of the animation
  50435. * @returns the {BABYLON.TargetedAnimation} object
  50436. */
  50437. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50438. var targetedAnimation = {
  50439. animation: animation,
  50440. target: target
  50441. };
  50442. var keys = animation.getKeys();
  50443. if (this._from > keys[0].frame) {
  50444. this._from = keys[0].frame;
  50445. }
  50446. if (this._to < keys[keys.length - 1].frame) {
  50447. this._to = keys[keys.length - 1].frame;
  50448. }
  50449. this._targetedAnimations.push(targetedAnimation);
  50450. return targetedAnimation;
  50451. };
  50452. /**
  50453. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50454. * It can add constant keys at begin or end
  50455. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50456. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50457. */
  50458. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50459. if (beginFrame === void 0) { beginFrame = null; }
  50460. if (endFrame === void 0) { endFrame = null; }
  50461. if (beginFrame == null)
  50462. beginFrame = this._from;
  50463. if (endFrame == null)
  50464. endFrame = this._to;
  50465. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50466. var targetedAnimation = this._targetedAnimations[index];
  50467. var keys = targetedAnimation.animation.getKeys();
  50468. var startKey = keys[0];
  50469. var endKey = keys[keys.length - 1];
  50470. if (startKey.frame > beginFrame) {
  50471. var newKey = {
  50472. frame: beginFrame,
  50473. value: startKey.value,
  50474. inTangent: startKey.inTangent,
  50475. outTangent: startKey.outTangent,
  50476. interpolation: startKey.interpolation
  50477. };
  50478. keys.splice(0, 0, newKey);
  50479. }
  50480. if (endKey.frame < endFrame) {
  50481. var newKey = {
  50482. frame: endFrame,
  50483. value: endKey.value,
  50484. inTangent: endKey.outTangent,
  50485. outTangent: endKey.outTangent,
  50486. interpolation: endKey.interpolation
  50487. };
  50488. keys.push(newKey);
  50489. }
  50490. }
  50491. this._from = beginFrame;
  50492. this._to = endFrame;
  50493. return this;
  50494. };
  50495. /**
  50496. * Start all animations on given targets
  50497. * @param loop defines if animations must loop
  50498. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50499. * @param from defines the from key (optional)
  50500. * @param to defines the to key (optional)
  50501. * @returns the current animation group
  50502. */
  50503. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50504. var _this = this;
  50505. if (loop === void 0) { loop = false; }
  50506. if (speedRatio === void 0) { speedRatio = 1; }
  50507. if (this._isStarted || this._targetedAnimations.length === 0) {
  50508. return this;
  50509. }
  50510. var _loop_1 = function (targetedAnimation) {
  50511. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50512. animatable.onAnimationEnd = function () {
  50513. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50514. _this._checkAnimationGroupEnded(animatable);
  50515. };
  50516. this_1._animatables.push(animatable);
  50517. };
  50518. var this_1 = this;
  50519. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50520. var targetedAnimation = _a[_i];
  50521. _loop_1(targetedAnimation);
  50522. }
  50523. this._speedRatio = speedRatio;
  50524. this._isStarted = true;
  50525. return this;
  50526. };
  50527. /**
  50528. * Pause all animations
  50529. */
  50530. AnimationGroup.prototype.pause = function () {
  50531. if (!this._isStarted) {
  50532. return this;
  50533. }
  50534. for (var index = 0; index < this._animatables.length; index++) {
  50535. var animatable = this._animatables[index];
  50536. animatable.pause();
  50537. }
  50538. return this;
  50539. };
  50540. /**
  50541. * Play all animations to initial state
  50542. * This function will start() the animations if they were not started or will restart() them if they were paused
  50543. * @param loop defines if animations must loop
  50544. */
  50545. AnimationGroup.prototype.play = function (loop) {
  50546. // only if all animatables are ready and exist
  50547. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50548. if (loop !== undefined) {
  50549. for (var index = 0; index < this._animatables.length; index++) {
  50550. var animatable = this._animatables[index];
  50551. animatable.loopAnimation = loop;
  50552. }
  50553. }
  50554. this.restart();
  50555. }
  50556. else {
  50557. this.stop();
  50558. this.start(loop, this._speedRatio);
  50559. }
  50560. return this;
  50561. };
  50562. /**
  50563. * Reset all animations to initial state
  50564. */
  50565. AnimationGroup.prototype.reset = function () {
  50566. if (!this._isStarted) {
  50567. return this;
  50568. }
  50569. for (var index = 0; index < this._animatables.length; index++) {
  50570. var animatable = this._animatables[index];
  50571. animatable.reset();
  50572. }
  50573. return this;
  50574. };
  50575. /**
  50576. * Restart animations from key 0
  50577. */
  50578. AnimationGroup.prototype.restart = function () {
  50579. if (!this._isStarted) {
  50580. return this;
  50581. }
  50582. for (var index = 0; index < this._animatables.length; index++) {
  50583. var animatable = this._animatables[index];
  50584. animatable.restart();
  50585. }
  50586. return this;
  50587. };
  50588. /**
  50589. * Stop all animations
  50590. */
  50591. AnimationGroup.prototype.stop = function () {
  50592. if (!this._isStarted) {
  50593. return this;
  50594. }
  50595. var list = this._animatables.slice();
  50596. for (var index = 0; index < list.length; index++) {
  50597. list[index].stop();
  50598. }
  50599. this._isStarted = false;
  50600. return this;
  50601. };
  50602. /**
  50603. * Set animation weight for all animatables
  50604. * @param weight defines the weight to use
  50605. * @return the animationGroup
  50606. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50607. */
  50608. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50609. for (var index = 0; index < this._animatables.length; index++) {
  50610. var animatable = this._animatables[index];
  50611. animatable.weight = weight;
  50612. }
  50613. return this;
  50614. };
  50615. /**
  50616. * Synchronize and normalize all animatables with a source animatable
  50617. * @param root defines the root animatable to synchronize with
  50618. * @return the animationGroup
  50619. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50620. */
  50621. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50622. for (var index = 0; index < this._animatables.length; index++) {
  50623. var animatable = this._animatables[index];
  50624. animatable.syncWith(root);
  50625. }
  50626. return this;
  50627. };
  50628. /**
  50629. * Goes to a specific frame in this animation group
  50630. * @param frame the frame number to go to
  50631. * @return the animationGroup
  50632. */
  50633. AnimationGroup.prototype.goToFrame = function (frame) {
  50634. if (!this._isStarted) {
  50635. return this;
  50636. }
  50637. for (var index = 0; index < this._animatables.length; index++) {
  50638. var animatable = this._animatables[index];
  50639. animatable.goToFrame(frame);
  50640. }
  50641. return this;
  50642. };
  50643. /**
  50644. * Dispose all associated resources
  50645. */
  50646. AnimationGroup.prototype.dispose = function () {
  50647. this._targetedAnimations = [];
  50648. this._animatables = [];
  50649. var index = this._scene.animationGroups.indexOf(this);
  50650. if (index > -1) {
  50651. this._scene.animationGroups.splice(index, 1);
  50652. }
  50653. };
  50654. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50655. // animatable should be taken out of the array
  50656. var idx = this._animatables.indexOf(animatable);
  50657. if (idx > -1) {
  50658. this._animatables.splice(idx, 1);
  50659. }
  50660. // all animatables were removed? animation group ended!
  50661. if (this._animatables.length === 0) {
  50662. this._isStarted = false;
  50663. this.onAnimationGroupEndObservable.notifyObservers(this);
  50664. }
  50665. };
  50666. return AnimationGroup;
  50667. }());
  50668. BABYLON.AnimationGroup = AnimationGroup;
  50669. })(BABYLON || (BABYLON = {}));
  50670. //# sourceMappingURL=babylon.animationGroup.js.map
  50671. var BABYLON;
  50672. (function (BABYLON) {
  50673. /**
  50674. * Defines a runtime animation
  50675. */
  50676. var RuntimeAnimation = /** @class */ (function () {
  50677. /**
  50678. * Create a new RuntimeAnimation object
  50679. * @param target defines the target of the animation
  50680. * @param animation defines the source animation object
  50681. * @param scene defines the hosting scene
  50682. * @param host defines the initiating Animatable
  50683. */
  50684. function RuntimeAnimation(target, animation, scene, host) {
  50685. var _this = this;
  50686. this._events = new Array();
  50687. /**
  50688. * The current frame of the runtime animation
  50689. */
  50690. this._currentFrame = 0;
  50691. /**
  50692. * The original value of the runtime animation
  50693. */
  50694. this._originalValue = new Array();
  50695. /**
  50696. * The offsets cache of the runtime animation
  50697. */
  50698. this._offsetsCache = {};
  50699. /**
  50700. * The high limits cache of the runtime animation
  50701. */
  50702. this._highLimitsCache = {};
  50703. /**
  50704. * Specifies if the runtime animation has been stopped
  50705. */
  50706. this._stopped = false;
  50707. /**
  50708. * The blending factor of the runtime animation
  50709. */
  50710. this._blendingFactor = 0;
  50711. /**
  50712. * The target path of the runtime animation
  50713. */
  50714. this._targetPath = "";
  50715. /**
  50716. * The weight of the runtime animation
  50717. */
  50718. this._weight = 1.0;
  50719. /**
  50720. * The ratio offset of the runtime animation
  50721. */
  50722. this._ratioOffset = 0;
  50723. /**
  50724. * The previous delay of the runtime animation
  50725. */
  50726. this._previousDelay = 0;
  50727. /**
  50728. * The previous ratio of the runtime animation
  50729. */
  50730. this._previousRatio = 0;
  50731. this._animation = animation;
  50732. this._target = target;
  50733. this._scene = scene;
  50734. this._host = host;
  50735. animation._runtimeAnimations.push(this);
  50736. // Cloning events locally
  50737. var events = animation.getEvents();
  50738. if (events && events.length > 0) {
  50739. events.forEach(function (e) {
  50740. _this._events.push(e._clone());
  50741. });
  50742. }
  50743. }
  50744. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50745. /**
  50746. * Gets the current frame of the runtime animation
  50747. */
  50748. get: function () {
  50749. return this._currentFrame;
  50750. },
  50751. enumerable: true,
  50752. configurable: true
  50753. });
  50754. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50755. /**
  50756. * Gets the weight of the runtime animation
  50757. */
  50758. get: function () {
  50759. return this._weight;
  50760. },
  50761. enumerable: true,
  50762. configurable: true
  50763. });
  50764. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50765. /**
  50766. * Gets the current value of the runtime animation
  50767. */
  50768. get: function () {
  50769. return this._currentValue;
  50770. },
  50771. enumerable: true,
  50772. configurable: true
  50773. });
  50774. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50775. /**
  50776. * Gets the target path of the runtime animation
  50777. */
  50778. get: function () {
  50779. return this._targetPath;
  50780. },
  50781. enumerable: true,
  50782. configurable: true
  50783. });
  50784. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50785. /**
  50786. * Gets the actual target of the runtime animation
  50787. */
  50788. get: function () {
  50789. return this._activeTarget;
  50790. },
  50791. enumerable: true,
  50792. configurable: true
  50793. });
  50794. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50795. /**
  50796. * Gets the animation from the runtime animation
  50797. */
  50798. get: function () {
  50799. return this._animation;
  50800. },
  50801. enumerable: true,
  50802. configurable: true
  50803. });
  50804. /**
  50805. * Resets the runtime animation to the beginning
  50806. * @param restoreOriginal defines whether to restore the target property to the original value
  50807. */
  50808. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50809. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50810. if (restoreOriginal) {
  50811. if (this._target instanceof Array) {
  50812. var index = 0;
  50813. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50814. var target = _a[_i];
  50815. if (this._originalValue[index] !== undefined) {
  50816. this._setValue(target, this._originalValue[index], -1);
  50817. }
  50818. index++;
  50819. }
  50820. }
  50821. else {
  50822. if (this._originalValue[0] !== undefined) {
  50823. this._setValue(this._target, this._originalValue[0], -1);
  50824. }
  50825. }
  50826. }
  50827. this._offsetsCache = {};
  50828. this._highLimitsCache = {};
  50829. this._currentFrame = 0;
  50830. this._blendingFactor = 0;
  50831. this._originalValue = new Array();
  50832. // Events
  50833. for (var index = 0; index < this._events.length; index++) {
  50834. this._events[index].isDone = false;
  50835. }
  50836. };
  50837. /**
  50838. * Specifies if the runtime animation is stopped
  50839. * @returns Boolean specifying if the runtime animation is stopped
  50840. */
  50841. RuntimeAnimation.prototype.isStopped = function () {
  50842. return this._stopped;
  50843. };
  50844. /**
  50845. * Disposes of the runtime animation
  50846. */
  50847. RuntimeAnimation.prototype.dispose = function () {
  50848. var index = this._animation.runtimeAnimations.indexOf(this);
  50849. if (index > -1) {
  50850. this._animation.runtimeAnimations.splice(index, 1);
  50851. }
  50852. };
  50853. /**
  50854. * Interpolates the animation from the current frame
  50855. * @param currentFrame The frame to interpolate the animation to
  50856. * @param repeatCount The number of times that the animation should loop
  50857. * @param loopMode The type of looping mode to use
  50858. * @param offsetValue Animation offset value
  50859. * @param highLimitValue The high limit value
  50860. * @returns The interpolated value
  50861. */
  50862. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50863. this._currentFrame = currentFrame;
  50864. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  50865. this._workValue = BABYLON.Matrix.Zero();
  50866. }
  50867. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  50868. };
  50869. /**
  50870. * Apply the interpolated value to the target
  50871. * @param currentValue defines the value computed by the animation
  50872. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  50873. */
  50874. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50875. if (weight === void 0) { weight = 1.0; }
  50876. if (this._target instanceof Array) {
  50877. var index = 0;
  50878. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50879. var target = _a[_i];
  50880. this._setValue(target, currentValue, weight, index);
  50881. index++;
  50882. }
  50883. }
  50884. else {
  50885. this._setValue(this._target, currentValue, weight);
  50886. }
  50887. };
  50888. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  50889. if (targetIndex === void 0) { targetIndex = 0; }
  50890. // Set value
  50891. var path;
  50892. var destination;
  50893. var targetPropertyPath = this._animation.targetPropertyPath;
  50894. if (targetPropertyPath.length > 1) {
  50895. var property = target[targetPropertyPath[0]];
  50896. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50897. property = property[targetPropertyPath[index]];
  50898. }
  50899. path = targetPropertyPath[targetPropertyPath.length - 1];
  50900. destination = property;
  50901. }
  50902. else {
  50903. path = targetPropertyPath[0];
  50904. destination = target;
  50905. }
  50906. this._targetPath = path;
  50907. this._activeTarget = destination;
  50908. this._weight = weight;
  50909. if (this._originalValue[targetIndex] === undefined) {
  50910. var originalValue = void 0;
  50911. if (destination.getRestPose && path === "_matrix") { // For bones
  50912. originalValue = destination.getRestPose();
  50913. }
  50914. else {
  50915. originalValue = destination[path];
  50916. }
  50917. if (originalValue && originalValue.clone) {
  50918. this._originalValue[targetIndex] = originalValue.clone();
  50919. }
  50920. else {
  50921. this._originalValue[targetIndex] = originalValue;
  50922. }
  50923. }
  50924. // Blending
  50925. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50926. if (enableBlending && this._blendingFactor <= 1.0) {
  50927. if (!this._originalBlendValue) {
  50928. var originalValue = destination[path];
  50929. if (originalValue.clone) {
  50930. this._originalBlendValue = originalValue.clone();
  50931. }
  50932. else {
  50933. this._originalBlendValue = originalValue;
  50934. }
  50935. }
  50936. if (this._originalBlendValue.m) { // Matrix
  50937. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  50938. if (this._currentValue) {
  50939. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50940. }
  50941. else {
  50942. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50943. }
  50944. }
  50945. else {
  50946. if (this._currentValue) {
  50947. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50948. }
  50949. else {
  50950. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50951. }
  50952. }
  50953. }
  50954. else {
  50955. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50956. }
  50957. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  50958. this._blendingFactor += blendingSpeed;
  50959. }
  50960. else {
  50961. this._currentValue = currentValue;
  50962. }
  50963. if (weight !== -1.0) {
  50964. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  50965. }
  50966. else {
  50967. destination[path] = this._currentValue;
  50968. }
  50969. if (target.markAsDirty) {
  50970. target.markAsDirty(this._animation.targetProperty);
  50971. }
  50972. };
  50973. /**
  50974. * Gets the loop pmode of the runtime animation
  50975. * @returns Loop Mode
  50976. */
  50977. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  50978. if (this._target && this._target.animationPropertiesOverride) {
  50979. return this._target.animationPropertiesOverride.loopMode;
  50980. }
  50981. return this._animation.loopMode;
  50982. };
  50983. /**
  50984. * Move the current animation to a given frame
  50985. * @param frame defines the frame to move to
  50986. */
  50987. RuntimeAnimation.prototype.goToFrame = function (frame) {
  50988. var keys = this._animation.getKeys();
  50989. if (frame < keys[0].frame) {
  50990. frame = keys[0].frame;
  50991. }
  50992. else if (frame > keys[keys.length - 1].frame) {
  50993. frame = keys[keys.length - 1].frame;
  50994. }
  50995. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  50996. this.setValue(currentValue, -1);
  50997. };
  50998. /**
  50999. * @hidden Internal use only
  51000. */
  51001. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51002. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51003. this._ratioOffset = this._previousRatio - newRatio;
  51004. };
  51005. /**
  51006. * Execute the current animation
  51007. * @param delay defines the delay to add to the current frame
  51008. * @param from defines the lower bound of the animation range
  51009. * @param to defines the upper bound of the animation range
  51010. * @param loop defines if the current animation must loop
  51011. * @param speedRatio defines the current speed ratio
  51012. * @param weight defines the weight of the animation (default is -1 so no weight)
  51013. * @returns a boolean indicating if the animation has ended
  51014. */
  51015. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51016. if (weight === void 0) { weight = -1.0; }
  51017. var targetPropertyPath = this._animation.targetPropertyPath;
  51018. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51019. this._stopped = true;
  51020. return false;
  51021. }
  51022. var returnValue = true;
  51023. var keys = this._animation.getKeys();
  51024. // Adding a start key at frame 0 if missing
  51025. if (keys[0].frame !== 0) {
  51026. var newKey = { frame: 0, value: keys[0].value };
  51027. keys.splice(0, 0, newKey);
  51028. }
  51029. // Check limits
  51030. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51031. from = keys[0].frame;
  51032. }
  51033. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51034. to = keys[keys.length - 1].frame;
  51035. }
  51036. //to and from cannot be the same key
  51037. if (from === to) {
  51038. if (from > keys[0].frame) {
  51039. from--;
  51040. }
  51041. else if (to < keys[keys.length - 1].frame) {
  51042. to++;
  51043. }
  51044. }
  51045. // Compute ratio
  51046. var range = to - from;
  51047. var offsetValue;
  51048. // ratio represents the frame delta between from and to
  51049. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51050. var highLimitValue = 0;
  51051. this._previousDelay = delay;
  51052. this._previousRatio = ratio;
  51053. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51054. returnValue = false;
  51055. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51056. }
  51057. else {
  51058. // Get max value if required
  51059. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51060. var keyOffset = to.toString() + from.toString();
  51061. if (!this._offsetsCache[keyOffset]) {
  51062. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51063. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51064. switch (this._animation.dataType) {
  51065. // Float
  51066. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51067. this._offsetsCache[keyOffset] = toValue - fromValue;
  51068. break;
  51069. // Quaternion
  51070. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51071. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51072. break;
  51073. // Vector3
  51074. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51075. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51076. // Vector2
  51077. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51078. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51079. // Size
  51080. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51081. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51082. // Color3
  51083. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51084. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51085. default:
  51086. break;
  51087. }
  51088. this._highLimitsCache[keyOffset] = toValue;
  51089. }
  51090. highLimitValue = this._highLimitsCache[keyOffset];
  51091. offsetValue = this._offsetsCache[keyOffset];
  51092. }
  51093. }
  51094. if (offsetValue === undefined) {
  51095. switch (this._animation.dataType) {
  51096. // Float
  51097. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51098. offsetValue = 0;
  51099. break;
  51100. // Quaternion
  51101. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51102. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51103. break;
  51104. // Vector3
  51105. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51106. offsetValue = BABYLON.Vector3.Zero();
  51107. break;
  51108. // Vector2
  51109. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51110. offsetValue = BABYLON.Vector2.Zero();
  51111. break;
  51112. // Size
  51113. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51114. offsetValue = BABYLON.Size.Zero();
  51115. break;
  51116. // Color3
  51117. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51118. offsetValue = BABYLON.Color3.Black();
  51119. }
  51120. }
  51121. // Compute value
  51122. var repeatCount = (ratio / range) >> 0;
  51123. var currentFrame = returnValue ? from + ratio % range : to;
  51124. // Need to normalize?
  51125. if (this._host && this._host.syncRoot) {
  51126. var syncRoot = this._host.syncRoot;
  51127. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51128. currentFrame = from + (to - from) * hostNormalizedFrame;
  51129. }
  51130. // Reset events if looping
  51131. var events = this._events;
  51132. if (range > 0 && this.currentFrame > currentFrame ||
  51133. range < 0 && this.currentFrame < currentFrame) {
  51134. // Need to reset animation events
  51135. for (var index = 0; index < events.length; index++) {
  51136. if (!events[index].onlyOnce) {
  51137. // reset event, the animation is looping
  51138. events[index].isDone = false;
  51139. }
  51140. }
  51141. }
  51142. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51143. // Set value
  51144. this.setValue(currentValue, weight);
  51145. // Check events
  51146. for (var index = 0; index < events.length; index++) {
  51147. // Make sure current frame has passed event frame and that event frame is within the current range
  51148. // Also, handle both forward and reverse animations
  51149. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51150. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51151. var event = events[index];
  51152. if (!event.isDone) {
  51153. // If event should be done only once, remove it.
  51154. if (event.onlyOnce) {
  51155. events.splice(index, 1);
  51156. index--;
  51157. }
  51158. event.isDone = true;
  51159. event.action();
  51160. } // Don't do anything if the event has already be done.
  51161. }
  51162. }
  51163. if (!returnValue) {
  51164. this._stopped = true;
  51165. }
  51166. return returnValue;
  51167. };
  51168. return RuntimeAnimation;
  51169. }());
  51170. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51171. })(BABYLON || (BABYLON = {}));
  51172. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51173. var BABYLON;
  51174. (function (BABYLON) {
  51175. var Animatable = /** @class */ (function () {
  51176. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  51177. if (fromFrame === void 0) { fromFrame = 0; }
  51178. if (toFrame === void 0) { toFrame = 100; }
  51179. if (loopAnimation === void 0) { loopAnimation = false; }
  51180. if (speedRatio === void 0) { speedRatio = 1.0; }
  51181. this.target = target;
  51182. this.fromFrame = fromFrame;
  51183. this.toFrame = toFrame;
  51184. this.loopAnimation = loopAnimation;
  51185. this.onAnimationEnd = onAnimationEnd;
  51186. this._localDelayOffset = null;
  51187. this._pausedDelay = null;
  51188. this._runtimeAnimations = new Array();
  51189. this._paused = false;
  51190. this._speedRatio = 1;
  51191. this._weight = -1.0;
  51192. this.animationStarted = false;
  51193. /**
  51194. * Observer raised when the animation ends
  51195. */
  51196. this.onAnimationEndObservable = new BABYLON.Observable();
  51197. this._scene = scene;
  51198. if (animations) {
  51199. this.appendAnimations(target, animations);
  51200. }
  51201. this._speedRatio = speedRatio;
  51202. scene._activeAnimatables.push(this);
  51203. }
  51204. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51205. /**
  51206. * Gets the root Animatable used to synchronize and normalize animations
  51207. */
  51208. get: function () {
  51209. return this._syncRoot;
  51210. },
  51211. enumerable: true,
  51212. configurable: true
  51213. });
  51214. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51215. /**
  51216. * Gets the current frame of the first RuntimeAnimation
  51217. * Used to synchronize Animatables
  51218. */
  51219. get: function () {
  51220. if (this._runtimeAnimations.length === 0) {
  51221. return 0;
  51222. }
  51223. return this._runtimeAnimations[0].currentFrame;
  51224. },
  51225. enumerable: true,
  51226. configurable: true
  51227. });
  51228. Object.defineProperty(Animatable.prototype, "weight", {
  51229. /**
  51230. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51231. */
  51232. get: function () {
  51233. return this._weight;
  51234. },
  51235. set: function (value) {
  51236. if (value === -1) { // -1 is ok and means no weight
  51237. this._weight = -1;
  51238. return;
  51239. }
  51240. // Else weight must be in [0, 1] range
  51241. this._weight = Math.min(Math.max(value, 0), 1.0);
  51242. },
  51243. enumerable: true,
  51244. configurable: true
  51245. });
  51246. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51247. /**
  51248. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51249. */
  51250. get: function () {
  51251. return this._speedRatio;
  51252. },
  51253. set: function (value) {
  51254. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51255. var animation = this._runtimeAnimations[index];
  51256. animation._prepareForSpeedRatioChange(value);
  51257. }
  51258. this._speedRatio = value;
  51259. },
  51260. enumerable: true,
  51261. configurable: true
  51262. });
  51263. // Methods
  51264. /**
  51265. * Synchronize and normalize current Animatable with a source Animatable
  51266. * This is useful when using animation weights and when animations are not of the same length
  51267. * @param root defines the root Animatable to synchronize with
  51268. * @returns the current Animatable
  51269. */
  51270. Animatable.prototype.syncWith = function (root) {
  51271. this._syncRoot = root;
  51272. if (root) {
  51273. // Make sure this animatable will animate after the root
  51274. var index = this._scene._activeAnimatables.indexOf(this);
  51275. if (index > -1) {
  51276. this._scene._activeAnimatables.splice(index, 1);
  51277. this._scene._activeAnimatables.push(this);
  51278. }
  51279. }
  51280. return this;
  51281. };
  51282. Animatable.prototype.getAnimations = function () {
  51283. return this._runtimeAnimations;
  51284. };
  51285. Animatable.prototype.appendAnimations = function (target, animations) {
  51286. for (var index = 0; index < animations.length; index++) {
  51287. var animation = animations[index];
  51288. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51289. }
  51290. };
  51291. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51292. var runtimeAnimations = this._runtimeAnimations;
  51293. for (var index = 0; index < runtimeAnimations.length; index++) {
  51294. if (runtimeAnimations[index].animation.targetProperty === property) {
  51295. return runtimeAnimations[index].animation;
  51296. }
  51297. }
  51298. return null;
  51299. };
  51300. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51301. var runtimeAnimations = this._runtimeAnimations;
  51302. for (var index = 0; index < runtimeAnimations.length; index++) {
  51303. if (runtimeAnimations[index].animation.targetProperty === property) {
  51304. return runtimeAnimations[index];
  51305. }
  51306. }
  51307. return null;
  51308. };
  51309. Animatable.prototype.reset = function () {
  51310. var runtimeAnimations = this._runtimeAnimations;
  51311. for (var index = 0; index < runtimeAnimations.length; index++) {
  51312. runtimeAnimations[index].reset(true);
  51313. }
  51314. this._localDelayOffset = null;
  51315. this._pausedDelay = null;
  51316. };
  51317. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51318. var runtimeAnimations = this._runtimeAnimations;
  51319. for (var index = 0; index < runtimeAnimations.length; index++) {
  51320. runtimeAnimations[index].animation.enableBlending = true;
  51321. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51322. }
  51323. };
  51324. Animatable.prototype.disableBlending = function () {
  51325. var runtimeAnimations = this._runtimeAnimations;
  51326. for (var index = 0; index < runtimeAnimations.length; index++) {
  51327. runtimeAnimations[index].animation.enableBlending = false;
  51328. }
  51329. };
  51330. Animatable.prototype.goToFrame = function (frame) {
  51331. var runtimeAnimations = this._runtimeAnimations;
  51332. if (runtimeAnimations[0]) {
  51333. var fps = runtimeAnimations[0].animation.framePerSecond;
  51334. var currentFrame = runtimeAnimations[0].currentFrame;
  51335. var adjustTime = frame - currentFrame;
  51336. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51337. if (this._localDelayOffset === null) {
  51338. this._localDelayOffset = 0;
  51339. }
  51340. this._localDelayOffset -= delay;
  51341. }
  51342. for (var index = 0; index < runtimeAnimations.length; index++) {
  51343. runtimeAnimations[index].goToFrame(frame);
  51344. }
  51345. };
  51346. Animatable.prototype.pause = function () {
  51347. if (this._paused) {
  51348. return;
  51349. }
  51350. this._paused = true;
  51351. };
  51352. Animatable.prototype.restart = function () {
  51353. this._paused = false;
  51354. };
  51355. Animatable.prototype._raiseOnAnimationEnd = function () {
  51356. if (this.onAnimationEnd) {
  51357. this.onAnimationEnd();
  51358. }
  51359. this.onAnimationEndObservable.notifyObservers(this);
  51360. };
  51361. Animatable.prototype.stop = function (animationName) {
  51362. if (animationName) {
  51363. var idx = this._scene._activeAnimatables.indexOf(this);
  51364. if (idx > -1) {
  51365. var runtimeAnimations = this._runtimeAnimations;
  51366. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51367. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  51368. continue;
  51369. }
  51370. runtimeAnimations[index].dispose();
  51371. runtimeAnimations.splice(index, 1);
  51372. }
  51373. if (runtimeAnimations.length == 0) {
  51374. this._scene._activeAnimatables.splice(idx, 1);
  51375. this._raiseOnAnimationEnd();
  51376. }
  51377. }
  51378. }
  51379. else {
  51380. var index = this._scene._activeAnimatables.indexOf(this);
  51381. if (index > -1) {
  51382. this._scene._activeAnimatables.splice(index, 1);
  51383. var runtimeAnimations = this._runtimeAnimations;
  51384. for (var index = 0; index < runtimeAnimations.length; index++) {
  51385. runtimeAnimations[index].dispose();
  51386. }
  51387. this._raiseOnAnimationEnd();
  51388. }
  51389. }
  51390. };
  51391. /**
  51392. * Wait asynchronously for the animation to end
  51393. * @returns a promise which will be fullfilled when the animation ends
  51394. */
  51395. Animatable.prototype.waitAsync = function () {
  51396. var _this = this;
  51397. return new Promise(function (resolve, reject) {
  51398. _this.onAnimationEndObservable.add(function () {
  51399. resolve(_this);
  51400. }, undefined, undefined, _this, true);
  51401. });
  51402. };
  51403. /** @hidden */
  51404. Animatable.prototype._animate = function (delay) {
  51405. if (this._paused) {
  51406. this.animationStarted = false;
  51407. if (this._pausedDelay === null) {
  51408. this._pausedDelay = delay;
  51409. }
  51410. return true;
  51411. }
  51412. if (this._localDelayOffset === null) {
  51413. this._localDelayOffset = delay;
  51414. this._pausedDelay = null;
  51415. }
  51416. else if (this._pausedDelay !== null) {
  51417. this._localDelayOffset += delay - this._pausedDelay;
  51418. this._pausedDelay = null;
  51419. }
  51420. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51421. return true;
  51422. }
  51423. // Animating
  51424. var running = false;
  51425. var runtimeAnimations = this._runtimeAnimations;
  51426. var index;
  51427. for (index = 0; index < runtimeAnimations.length; index++) {
  51428. var animation = runtimeAnimations[index];
  51429. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51430. running = running || isRunning;
  51431. }
  51432. this.animationStarted = running;
  51433. if (!running) {
  51434. // Remove from active animatables
  51435. index = this._scene._activeAnimatables.indexOf(this);
  51436. this._scene._activeAnimatables.splice(index, 1);
  51437. // Dispose all runtime animations
  51438. for (index = 0; index < runtimeAnimations.length; index++) {
  51439. runtimeAnimations[index].dispose();
  51440. }
  51441. this._raiseOnAnimationEnd();
  51442. this.onAnimationEnd = null;
  51443. this.onAnimationEndObservable.clear();
  51444. }
  51445. return running;
  51446. };
  51447. return Animatable;
  51448. }());
  51449. BABYLON.Animatable = Animatable;
  51450. })(BABYLON || (BABYLON = {}));
  51451. //# sourceMappingURL=babylon.animatable.js.map
  51452. var BABYLON;
  51453. (function (BABYLON) {
  51454. var EasingFunction = /** @class */ (function () {
  51455. function EasingFunction() {
  51456. // Properties
  51457. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51458. }
  51459. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51460. get: function () {
  51461. return EasingFunction._EASINGMODE_EASEIN;
  51462. },
  51463. enumerable: true,
  51464. configurable: true
  51465. });
  51466. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51467. get: function () {
  51468. return EasingFunction._EASINGMODE_EASEOUT;
  51469. },
  51470. enumerable: true,
  51471. configurable: true
  51472. });
  51473. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51474. get: function () {
  51475. return EasingFunction._EASINGMODE_EASEINOUT;
  51476. },
  51477. enumerable: true,
  51478. configurable: true
  51479. });
  51480. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51481. var n = Math.min(Math.max(easingMode, 0), 2);
  51482. this._easingMode = n;
  51483. };
  51484. EasingFunction.prototype.getEasingMode = function () {
  51485. return this._easingMode;
  51486. };
  51487. EasingFunction.prototype.easeInCore = function (gradient) {
  51488. throw new Error('You must implement this method');
  51489. };
  51490. EasingFunction.prototype.ease = function (gradient) {
  51491. switch (this._easingMode) {
  51492. case EasingFunction.EASINGMODE_EASEIN:
  51493. return this.easeInCore(gradient);
  51494. case EasingFunction.EASINGMODE_EASEOUT:
  51495. return (1 - this.easeInCore(1 - gradient));
  51496. }
  51497. if (gradient >= 0.5) {
  51498. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51499. }
  51500. return (this.easeInCore(gradient * 2) * 0.5);
  51501. };
  51502. //Statics
  51503. EasingFunction._EASINGMODE_EASEIN = 0;
  51504. EasingFunction._EASINGMODE_EASEOUT = 1;
  51505. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51506. return EasingFunction;
  51507. }());
  51508. BABYLON.EasingFunction = EasingFunction;
  51509. var CircleEase = /** @class */ (function (_super) {
  51510. __extends(CircleEase, _super);
  51511. function CircleEase() {
  51512. return _super !== null && _super.apply(this, arguments) || this;
  51513. }
  51514. CircleEase.prototype.easeInCore = function (gradient) {
  51515. gradient = Math.max(0, Math.min(1, gradient));
  51516. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51517. };
  51518. return CircleEase;
  51519. }(EasingFunction));
  51520. BABYLON.CircleEase = CircleEase;
  51521. var BackEase = /** @class */ (function (_super) {
  51522. __extends(BackEase, _super);
  51523. function BackEase(amplitude) {
  51524. if (amplitude === void 0) { amplitude = 1; }
  51525. var _this = _super.call(this) || this;
  51526. _this.amplitude = amplitude;
  51527. return _this;
  51528. }
  51529. BackEase.prototype.easeInCore = function (gradient) {
  51530. var num = Math.max(0, this.amplitude);
  51531. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51532. };
  51533. return BackEase;
  51534. }(EasingFunction));
  51535. BABYLON.BackEase = BackEase;
  51536. var BounceEase = /** @class */ (function (_super) {
  51537. __extends(BounceEase, _super);
  51538. function BounceEase(bounces, bounciness) {
  51539. if (bounces === void 0) { bounces = 3; }
  51540. if (bounciness === void 0) { bounciness = 2; }
  51541. var _this = _super.call(this) || this;
  51542. _this.bounces = bounces;
  51543. _this.bounciness = bounciness;
  51544. return _this;
  51545. }
  51546. BounceEase.prototype.easeInCore = function (gradient) {
  51547. var y = Math.max(0.0, this.bounces);
  51548. var bounciness = this.bounciness;
  51549. if (bounciness <= 1.0) {
  51550. bounciness = 1.001;
  51551. }
  51552. var num9 = Math.pow(bounciness, y);
  51553. var num5 = 1.0 - bounciness;
  51554. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51555. var num15 = gradient * num4;
  51556. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51557. var num3 = Math.floor(num65);
  51558. var num13 = num3 + 1.0;
  51559. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51560. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51561. var num7 = (num8 + num12) * 0.5;
  51562. var num6 = gradient - num7;
  51563. var num2 = num7 - num8;
  51564. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51565. };
  51566. return BounceEase;
  51567. }(EasingFunction));
  51568. BABYLON.BounceEase = BounceEase;
  51569. var CubicEase = /** @class */ (function (_super) {
  51570. __extends(CubicEase, _super);
  51571. function CubicEase() {
  51572. return _super !== null && _super.apply(this, arguments) || this;
  51573. }
  51574. CubicEase.prototype.easeInCore = function (gradient) {
  51575. return (gradient * gradient * gradient);
  51576. };
  51577. return CubicEase;
  51578. }(EasingFunction));
  51579. BABYLON.CubicEase = CubicEase;
  51580. var ElasticEase = /** @class */ (function (_super) {
  51581. __extends(ElasticEase, _super);
  51582. function ElasticEase(oscillations, springiness) {
  51583. if (oscillations === void 0) { oscillations = 3; }
  51584. if (springiness === void 0) { springiness = 3; }
  51585. var _this = _super.call(this) || this;
  51586. _this.oscillations = oscillations;
  51587. _this.springiness = springiness;
  51588. return _this;
  51589. }
  51590. ElasticEase.prototype.easeInCore = function (gradient) {
  51591. var num2;
  51592. var num3 = Math.max(0.0, this.oscillations);
  51593. var num = Math.max(0.0, this.springiness);
  51594. if (num == 0) {
  51595. num2 = gradient;
  51596. }
  51597. else {
  51598. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51599. }
  51600. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51601. };
  51602. return ElasticEase;
  51603. }(EasingFunction));
  51604. BABYLON.ElasticEase = ElasticEase;
  51605. var ExponentialEase = /** @class */ (function (_super) {
  51606. __extends(ExponentialEase, _super);
  51607. function ExponentialEase(exponent) {
  51608. if (exponent === void 0) { exponent = 2; }
  51609. var _this = _super.call(this) || this;
  51610. _this.exponent = exponent;
  51611. return _this;
  51612. }
  51613. ExponentialEase.prototype.easeInCore = function (gradient) {
  51614. if (this.exponent <= 0) {
  51615. return gradient;
  51616. }
  51617. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51618. };
  51619. return ExponentialEase;
  51620. }(EasingFunction));
  51621. BABYLON.ExponentialEase = ExponentialEase;
  51622. var PowerEase = /** @class */ (function (_super) {
  51623. __extends(PowerEase, _super);
  51624. function PowerEase(power) {
  51625. if (power === void 0) { power = 2; }
  51626. var _this = _super.call(this) || this;
  51627. _this.power = power;
  51628. return _this;
  51629. }
  51630. PowerEase.prototype.easeInCore = function (gradient) {
  51631. var y = Math.max(0.0, this.power);
  51632. return Math.pow(gradient, y);
  51633. };
  51634. return PowerEase;
  51635. }(EasingFunction));
  51636. BABYLON.PowerEase = PowerEase;
  51637. var QuadraticEase = /** @class */ (function (_super) {
  51638. __extends(QuadraticEase, _super);
  51639. function QuadraticEase() {
  51640. return _super !== null && _super.apply(this, arguments) || this;
  51641. }
  51642. QuadraticEase.prototype.easeInCore = function (gradient) {
  51643. return (gradient * gradient);
  51644. };
  51645. return QuadraticEase;
  51646. }(EasingFunction));
  51647. BABYLON.QuadraticEase = QuadraticEase;
  51648. var QuarticEase = /** @class */ (function (_super) {
  51649. __extends(QuarticEase, _super);
  51650. function QuarticEase() {
  51651. return _super !== null && _super.apply(this, arguments) || this;
  51652. }
  51653. QuarticEase.prototype.easeInCore = function (gradient) {
  51654. return (gradient * gradient * gradient * gradient);
  51655. };
  51656. return QuarticEase;
  51657. }(EasingFunction));
  51658. BABYLON.QuarticEase = QuarticEase;
  51659. var QuinticEase = /** @class */ (function (_super) {
  51660. __extends(QuinticEase, _super);
  51661. function QuinticEase() {
  51662. return _super !== null && _super.apply(this, arguments) || this;
  51663. }
  51664. QuinticEase.prototype.easeInCore = function (gradient) {
  51665. return (gradient * gradient * gradient * gradient * gradient);
  51666. };
  51667. return QuinticEase;
  51668. }(EasingFunction));
  51669. BABYLON.QuinticEase = QuinticEase;
  51670. var SineEase = /** @class */ (function (_super) {
  51671. __extends(SineEase, _super);
  51672. function SineEase() {
  51673. return _super !== null && _super.apply(this, arguments) || this;
  51674. }
  51675. SineEase.prototype.easeInCore = function (gradient) {
  51676. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51677. };
  51678. return SineEase;
  51679. }(EasingFunction));
  51680. BABYLON.SineEase = SineEase;
  51681. var BezierCurveEase = /** @class */ (function (_super) {
  51682. __extends(BezierCurveEase, _super);
  51683. function BezierCurveEase(x1, y1, x2, y2) {
  51684. if (x1 === void 0) { x1 = 0; }
  51685. if (y1 === void 0) { y1 = 0; }
  51686. if (x2 === void 0) { x2 = 1; }
  51687. if (y2 === void 0) { y2 = 1; }
  51688. var _this = _super.call(this) || this;
  51689. _this.x1 = x1;
  51690. _this.y1 = y1;
  51691. _this.x2 = x2;
  51692. _this.y2 = y2;
  51693. return _this;
  51694. }
  51695. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51696. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51697. };
  51698. return BezierCurveEase;
  51699. }(EasingFunction));
  51700. BABYLON.BezierCurveEase = BezierCurveEase;
  51701. })(BABYLON || (BABYLON = {}));
  51702. //# sourceMappingURL=babylon.easing.js.map
  51703. var BABYLON;
  51704. (function (BABYLON) {
  51705. /**
  51706. * A Condition applied to an Action
  51707. */
  51708. var Condition = /** @class */ (function () {
  51709. /**
  51710. * Creates a new Condition
  51711. * @param actionManager the manager of the action the condition is applied to
  51712. */
  51713. function Condition(actionManager) {
  51714. this._actionManager = actionManager;
  51715. }
  51716. /**
  51717. * Check if the current condition is valid
  51718. * @returns a boolean
  51719. */
  51720. Condition.prototype.isValid = function () {
  51721. return true;
  51722. };
  51723. /**
  51724. * Internal only
  51725. * @hidden
  51726. */
  51727. Condition.prototype._getProperty = function (propertyPath) {
  51728. return this._actionManager._getProperty(propertyPath);
  51729. };
  51730. /**
  51731. * Internal only
  51732. * @hidden
  51733. */
  51734. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51735. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51736. };
  51737. /**
  51738. * Serialize placeholder for child classes
  51739. * @returns the serialized object
  51740. */
  51741. Condition.prototype.serialize = function () {
  51742. };
  51743. /**
  51744. * Internal only
  51745. * @hidden
  51746. */
  51747. Condition.prototype._serialize = function (serializedCondition) {
  51748. return {
  51749. type: 2,
  51750. children: [],
  51751. name: serializedCondition.name,
  51752. properties: serializedCondition.properties
  51753. };
  51754. };
  51755. return Condition;
  51756. }());
  51757. BABYLON.Condition = Condition;
  51758. /**
  51759. * Defines specific conditional operators as extensions of Condition
  51760. */
  51761. var ValueCondition = /** @class */ (function (_super) {
  51762. __extends(ValueCondition, _super);
  51763. /**
  51764. * Creates a new ValueCondition
  51765. * @param actionManager manager for the action the condition applies to
  51766. * @param target for the action
  51767. * @param propertyPath path to specify the property of the target the conditional operator uses
  51768. * @param value the value compared by the conditional operator against the current value of the property
  51769. * @param operator the conditional operator, default ValueCondition.IsEqual
  51770. */
  51771. function ValueCondition(actionManager, target,
  51772. /** path to specify the property of the target the conditional operator uses */
  51773. propertyPath,
  51774. /** the value compared by the conditional operator against the current value of the property */
  51775. value,
  51776. /** the conditional operator, default ValueCondition.IsEqual */
  51777. operator) {
  51778. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51779. var _this = _super.call(this, actionManager) || this;
  51780. _this.propertyPath = propertyPath;
  51781. _this.value = value;
  51782. _this.operator = operator;
  51783. _this._target = target;
  51784. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51785. _this._property = _this._getProperty(_this.propertyPath);
  51786. return _this;
  51787. }
  51788. Object.defineProperty(ValueCondition, "IsEqual", {
  51789. /**
  51790. * returns the number for IsEqual
  51791. */
  51792. get: function () {
  51793. return ValueCondition._IsEqual;
  51794. },
  51795. enumerable: true,
  51796. configurable: true
  51797. });
  51798. Object.defineProperty(ValueCondition, "IsDifferent", {
  51799. /**
  51800. * Returns the number for IsDifferent
  51801. */
  51802. get: function () {
  51803. return ValueCondition._IsDifferent;
  51804. },
  51805. enumerable: true,
  51806. configurable: true
  51807. });
  51808. Object.defineProperty(ValueCondition, "IsGreater", {
  51809. /**
  51810. * Returns the number for IsGreater
  51811. */
  51812. get: function () {
  51813. return ValueCondition._IsGreater;
  51814. },
  51815. enumerable: true,
  51816. configurable: true
  51817. });
  51818. Object.defineProperty(ValueCondition, "IsLesser", {
  51819. /**
  51820. * Returns the number for IsLesser
  51821. */
  51822. get: function () {
  51823. return ValueCondition._IsLesser;
  51824. },
  51825. enumerable: true,
  51826. configurable: true
  51827. });
  51828. /**
  51829. * Compares the given value with the property value for the specified conditional operator
  51830. * @returns the result of the comparison
  51831. */
  51832. ValueCondition.prototype.isValid = function () {
  51833. switch (this.operator) {
  51834. case ValueCondition.IsGreater:
  51835. return this._effectiveTarget[this._property] > this.value;
  51836. case ValueCondition.IsLesser:
  51837. return this._effectiveTarget[this._property] < this.value;
  51838. case ValueCondition.IsEqual:
  51839. case ValueCondition.IsDifferent:
  51840. var check;
  51841. if (this.value.equals) {
  51842. check = this.value.equals(this._effectiveTarget[this._property]);
  51843. }
  51844. else {
  51845. check = this.value === this._effectiveTarget[this._property];
  51846. }
  51847. return this.operator === ValueCondition.IsEqual ? check : !check;
  51848. }
  51849. return false;
  51850. };
  51851. /**
  51852. * Serialize the ValueCondition into a JSON compatible object
  51853. * @returns serialization object
  51854. */
  51855. ValueCondition.prototype.serialize = function () {
  51856. return this._serialize({
  51857. name: "ValueCondition",
  51858. properties: [
  51859. BABYLON.Action._GetTargetProperty(this._target),
  51860. { name: "propertyPath", value: this.propertyPath },
  51861. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51862. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51863. ]
  51864. });
  51865. };
  51866. /**
  51867. * Gets the name of the conditional operator for the ValueCondition
  51868. * @param operator the conditional operator
  51869. * @returns the name
  51870. */
  51871. ValueCondition.GetOperatorName = function (operator) {
  51872. switch (operator) {
  51873. case ValueCondition._IsEqual: return "IsEqual";
  51874. case ValueCondition._IsDifferent: return "IsDifferent";
  51875. case ValueCondition._IsGreater: return "IsGreater";
  51876. case ValueCondition._IsLesser: return "IsLesser";
  51877. default: return "";
  51878. }
  51879. };
  51880. /**
  51881. * Internal only
  51882. * @hidden
  51883. */
  51884. ValueCondition._IsEqual = 0;
  51885. /**
  51886. * Internal only
  51887. * @hidden
  51888. */
  51889. ValueCondition._IsDifferent = 1;
  51890. /**
  51891. * Internal only
  51892. * @hidden
  51893. */
  51894. ValueCondition._IsGreater = 2;
  51895. /**
  51896. * Internal only
  51897. * @hidden
  51898. */
  51899. ValueCondition._IsLesser = 3;
  51900. return ValueCondition;
  51901. }(Condition));
  51902. BABYLON.ValueCondition = ValueCondition;
  51903. /**
  51904. * Defines a predicate condition as an extension of Condition
  51905. */
  51906. var PredicateCondition = /** @class */ (function (_super) {
  51907. __extends(PredicateCondition, _super);
  51908. /**
  51909. * Creates a new PredicateCondition
  51910. * @param actionManager manager for the action the condition applies to
  51911. * @param predicate defines the predicate function used to validate the condition
  51912. */
  51913. function PredicateCondition(actionManager,
  51914. /** defines the predicate function used to validate the condition */
  51915. predicate) {
  51916. var _this = _super.call(this, actionManager) || this;
  51917. _this.predicate = predicate;
  51918. return _this;
  51919. }
  51920. /**
  51921. * @returns the validity of the predicate condition
  51922. */
  51923. PredicateCondition.prototype.isValid = function () {
  51924. return this.predicate();
  51925. };
  51926. return PredicateCondition;
  51927. }(Condition));
  51928. BABYLON.PredicateCondition = PredicateCondition;
  51929. /**
  51930. * Defines a state condition as an extension of Condition
  51931. */
  51932. var StateCondition = /** @class */ (function (_super) {
  51933. __extends(StateCondition, _super);
  51934. /**
  51935. * Creates a new StateCondition
  51936. * @param actionManager manager for the action the condition applies to
  51937. * @param target of the condition
  51938. * @param value to compare with target state
  51939. */
  51940. function StateCondition(actionManager, target, value) {
  51941. var _this = _super.call(this, actionManager) || this;
  51942. _this.value = value;
  51943. _this._target = target;
  51944. return _this;
  51945. }
  51946. /**
  51947. * @returns the validity of the state
  51948. */
  51949. StateCondition.prototype.isValid = function () {
  51950. return this._target.state === this.value;
  51951. };
  51952. /**
  51953. * Serialize the StateCondition into a JSON compatible object
  51954. * @returns serialization object
  51955. */
  51956. StateCondition.prototype.serialize = function () {
  51957. return this._serialize({
  51958. name: "StateCondition",
  51959. properties: [
  51960. BABYLON.Action._GetTargetProperty(this._target),
  51961. { name: "value", value: this.value }
  51962. ]
  51963. });
  51964. };
  51965. return StateCondition;
  51966. }(Condition));
  51967. BABYLON.StateCondition = StateCondition;
  51968. })(BABYLON || (BABYLON = {}));
  51969. //# sourceMappingURL=babylon.condition.js.map
  51970. var BABYLON;
  51971. (function (BABYLON) {
  51972. /**
  51973. * The action to be carried out following a trigger
  51974. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  51975. */
  51976. var Action = /** @class */ (function () {
  51977. /**
  51978. * Creates a new Action
  51979. * @param triggerOptions the trigger, with or without parameters, for the action
  51980. * @param condition an optional determinant of action
  51981. */
  51982. function Action(
  51983. /** the trigger, with or without parameters, for the action */
  51984. triggerOptions, condition) {
  51985. this.triggerOptions = triggerOptions;
  51986. /**
  51987. * An event triggered prior to action being executed.
  51988. */
  51989. this.onBeforeExecuteObservable = new BABYLON.Observable();
  51990. if (triggerOptions.parameter) {
  51991. this.trigger = triggerOptions.trigger;
  51992. this._triggerParameter = triggerOptions.parameter;
  51993. }
  51994. else {
  51995. this.trigger = triggerOptions;
  51996. }
  51997. this._nextActiveAction = this;
  51998. this._condition = condition;
  51999. }
  52000. /**
  52001. * Internal only
  52002. * @hidden
  52003. */
  52004. Action.prototype._prepare = function () {
  52005. };
  52006. /**
  52007. * Gets the trigger parameters
  52008. * @returns the trigger parameters
  52009. */
  52010. Action.prototype.getTriggerParameter = function () {
  52011. return this._triggerParameter;
  52012. };
  52013. /**
  52014. * Internal only - executes current action event
  52015. * @hidden
  52016. */
  52017. Action.prototype._executeCurrent = function (evt) {
  52018. if (this._nextActiveAction._condition) {
  52019. var condition = this._nextActiveAction._condition;
  52020. var currentRenderId = this._actionManager.getScene().getRenderId();
  52021. // We cache the current evaluation for the current frame
  52022. if (condition._evaluationId === currentRenderId) {
  52023. if (!condition._currentResult) {
  52024. return;
  52025. }
  52026. }
  52027. else {
  52028. condition._evaluationId = currentRenderId;
  52029. if (!condition.isValid()) {
  52030. condition._currentResult = false;
  52031. return;
  52032. }
  52033. condition._currentResult = true;
  52034. }
  52035. }
  52036. this.onBeforeExecuteObservable.notifyObservers(this);
  52037. this._nextActiveAction.execute(evt);
  52038. this.skipToNextActiveAction();
  52039. };
  52040. /**
  52041. * Execute placeholder for child classes
  52042. * @param evt optional action event
  52043. */
  52044. Action.prototype.execute = function (evt) {
  52045. };
  52046. /**
  52047. * Skips to next active action
  52048. */
  52049. Action.prototype.skipToNextActiveAction = function () {
  52050. if (this._nextActiveAction._child) {
  52051. if (!this._nextActiveAction._child._actionManager) {
  52052. this._nextActiveAction._child._actionManager = this._actionManager;
  52053. }
  52054. this._nextActiveAction = this._nextActiveAction._child;
  52055. }
  52056. else {
  52057. this._nextActiveAction = this;
  52058. }
  52059. };
  52060. /**
  52061. * Adds action to chain of actions, may be a DoNothingAction
  52062. * @param action defines the next action to execute
  52063. * @returns The action passed in
  52064. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52065. */
  52066. Action.prototype.then = function (action) {
  52067. this._child = action;
  52068. action._actionManager = this._actionManager;
  52069. action._prepare();
  52070. return action;
  52071. };
  52072. /**
  52073. * Internal only
  52074. * @hidden
  52075. */
  52076. Action.prototype._getProperty = function (propertyPath) {
  52077. return this._actionManager._getProperty(propertyPath);
  52078. };
  52079. /**
  52080. * Internal only
  52081. * @hidden
  52082. */
  52083. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52084. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52085. };
  52086. /**
  52087. * Serialize placeholder for child classes
  52088. * @param parent of child
  52089. * @returns the serialized object
  52090. */
  52091. Action.prototype.serialize = function (parent) {
  52092. };
  52093. /**
  52094. * Internal only called by serialize
  52095. * @hidden
  52096. */
  52097. Action.prototype._serialize = function (serializedAction, parent) {
  52098. var serializationObject = {
  52099. type: 1,
  52100. children: [],
  52101. name: serializedAction.name,
  52102. properties: serializedAction.properties || []
  52103. };
  52104. // Serialize child
  52105. if (this._child) {
  52106. this._child.serialize(serializationObject);
  52107. }
  52108. // Check if "this" has a condition
  52109. if (this._condition) {
  52110. var serializedCondition = this._condition.serialize();
  52111. serializedCondition.children.push(serializationObject);
  52112. if (parent) {
  52113. parent.children.push(serializedCondition);
  52114. }
  52115. return serializedCondition;
  52116. }
  52117. if (parent) {
  52118. parent.children.push(serializationObject);
  52119. }
  52120. return serializationObject;
  52121. };
  52122. /**
  52123. * Internal only
  52124. * @hidden
  52125. */
  52126. Action._SerializeValueAsString = function (value) {
  52127. if (typeof value === "number") {
  52128. return value.toString();
  52129. }
  52130. if (typeof value === "boolean") {
  52131. return value ? "true" : "false";
  52132. }
  52133. if (value instanceof BABYLON.Vector2) {
  52134. return value.x + ", " + value.y;
  52135. }
  52136. if (value instanceof BABYLON.Vector3) {
  52137. return value.x + ", " + value.y + ", " + value.z;
  52138. }
  52139. if (value instanceof BABYLON.Color3) {
  52140. return value.r + ", " + value.g + ", " + value.b;
  52141. }
  52142. if (value instanceof BABYLON.Color4) {
  52143. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52144. }
  52145. return value; // string
  52146. };
  52147. /**
  52148. * Internal only
  52149. * @hidden
  52150. */
  52151. Action._GetTargetProperty = function (target) {
  52152. return {
  52153. name: "target",
  52154. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52155. : target instanceof BABYLON.Light ? "LightProperties"
  52156. : target instanceof BABYLON.Camera ? "CameraProperties"
  52157. : "SceneProperties",
  52158. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52159. };
  52160. };
  52161. return Action;
  52162. }());
  52163. BABYLON.Action = Action;
  52164. })(BABYLON || (BABYLON = {}));
  52165. //# sourceMappingURL=babylon.action.js.map
  52166. var BABYLON;
  52167. (function (BABYLON) {
  52168. /**
  52169. * ActionEvent is the event being sent when an action is triggered.
  52170. */
  52171. var ActionEvent = /** @class */ (function () {
  52172. /**
  52173. * Creates a new ActionEvent
  52174. * @param source The mesh or sprite that triggered the action
  52175. * @param pointerX The X mouse cursor position at the time of the event
  52176. * @param pointerY The Y mouse cursor position at the time of the event
  52177. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52178. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52179. * @param additionalData additional data for the event
  52180. */
  52181. function ActionEvent(
  52182. /** The mesh or sprite that triggered the action */
  52183. source,
  52184. /** The X mouse cursor position at the time of the event */
  52185. pointerX,
  52186. /** The Y mouse cursor position at the time of the event */
  52187. pointerY,
  52188. /** The mesh that is currently pointed at (can be null) */
  52189. meshUnderPointer,
  52190. /** the original (browser) event that triggered the ActionEvent */
  52191. sourceEvent,
  52192. /** additional data for the event */
  52193. additionalData) {
  52194. this.source = source;
  52195. this.pointerX = pointerX;
  52196. this.pointerY = pointerY;
  52197. this.meshUnderPointer = meshUnderPointer;
  52198. this.sourceEvent = sourceEvent;
  52199. this.additionalData = additionalData;
  52200. }
  52201. /**
  52202. * Helper function to auto-create an ActionEvent from a source mesh.
  52203. * @param source The source mesh that triggered the event
  52204. * @param evt The original (browser) event
  52205. * @param additionalData additional data for the event
  52206. * @returns the new ActionEvent
  52207. */
  52208. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52209. var scene = source.getScene();
  52210. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52211. };
  52212. /**
  52213. * Helper function to auto-create an ActionEvent from a source sprite
  52214. * @param source The source sprite that triggered the event
  52215. * @param scene Scene associated with the sprite
  52216. * @param evt The original (browser) event
  52217. * @param additionalData additional data for the event
  52218. * @returns the new ActionEvent
  52219. */
  52220. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52221. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52222. };
  52223. /**
  52224. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52225. * @param scene the scene where the event occurred
  52226. * @param evt The original (browser) event
  52227. * @returns the new ActionEvent
  52228. */
  52229. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52230. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52231. };
  52232. /**
  52233. * Helper function to auto-create an ActionEvent from a primitive
  52234. * @param prim defines the target primitive
  52235. * @param pointerPos defines the pointer position
  52236. * @param evt The original (browser) event
  52237. * @param additionalData additional data for the event
  52238. * @returns the new ActionEvent
  52239. */
  52240. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52241. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52242. };
  52243. return ActionEvent;
  52244. }());
  52245. BABYLON.ActionEvent = ActionEvent;
  52246. /**
  52247. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52248. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52249. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52250. */
  52251. var ActionManager = /** @class */ (function () {
  52252. /**
  52253. * Creates a new action manager
  52254. * @param scene defines the hosting scene
  52255. */
  52256. function ActionManager(scene) {
  52257. // Members
  52258. /** Gets the list of actions */
  52259. this.actions = new Array();
  52260. /** Gets the cursor to use when hovering items */
  52261. this.hoverCursor = '';
  52262. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52263. scene._actionManagers.push(this);
  52264. }
  52265. Object.defineProperty(ActionManager, "NothingTrigger", {
  52266. /**
  52267. * Nothing
  52268. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52269. */
  52270. get: function () {
  52271. return ActionManager._NothingTrigger;
  52272. },
  52273. enumerable: true,
  52274. configurable: true
  52275. });
  52276. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52277. /**
  52278. * On pick
  52279. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52280. */
  52281. get: function () {
  52282. return ActionManager._OnPickTrigger;
  52283. },
  52284. enumerable: true,
  52285. configurable: true
  52286. });
  52287. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52288. /**
  52289. * On left pick
  52290. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52291. */
  52292. get: function () {
  52293. return ActionManager._OnLeftPickTrigger;
  52294. },
  52295. enumerable: true,
  52296. configurable: true
  52297. });
  52298. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52299. /**
  52300. * On right pick
  52301. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52302. */
  52303. get: function () {
  52304. return ActionManager._OnRightPickTrigger;
  52305. },
  52306. enumerable: true,
  52307. configurable: true
  52308. });
  52309. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52310. /**
  52311. * On center pick
  52312. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52313. */
  52314. get: function () {
  52315. return ActionManager._OnCenterPickTrigger;
  52316. },
  52317. enumerable: true,
  52318. configurable: true
  52319. });
  52320. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52321. /**
  52322. * On pick down
  52323. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52324. */
  52325. get: function () {
  52326. return ActionManager._OnPickDownTrigger;
  52327. },
  52328. enumerable: true,
  52329. configurable: true
  52330. });
  52331. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52332. /**
  52333. * On double pick
  52334. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52335. */
  52336. get: function () {
  52337. return ActionManager._OnDoublePickTrigger;
  52338. },
  52339. enumerable: true,
  52340. configurable: true
  52341. });
  52342. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52343. /**
  52344. * On pick up
  52345. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52346. */
  52347. get: function () {
  52348. return ActionManager._OnPickUpTrigger;
  52349. },
  52350. enumerable: true,
  52351. configurable: true
  52352. });
  52353. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52354. /**
  52355. * On pick out.
  52356. * This trigger will only be raised if you also declared a OnPickDown
  52357. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52358. */
  52359. get: function () {
  52360. return ActionManager._OnPickOutTrigger;
  52361. },
  52362. enumerable: true,
  52363. configurable: true
  52364. });
  52365. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52366. /**
  52367. * On long press
  52368. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52369. */
  52370. get: function () {
  52371. return ActionManager._OnLongPressTrigger;
  52372. },
  52373. enumerable: true,
  52374. configurable: true
  52375. });
  52376. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52377. /**
  52378. * On pointer over
  52379. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52380. */
  52381. get: function () {
  52382. return ActionManager._OnPointerOverTrigger;
  52383. },
  52384. enumerable: true,
  52385. configurable: true
  52386. });
  52387. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52388. /**
  52389. * On pointer out
  52390. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52391. */
  52392. get: function () {
  52393. return ActionManager._OnPointerOutTrigger;
  52394. },
  52395. enumerable: true,
  52396. configurable: true
  52397. });
  52398. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52399. /**
  52400. * On every frame
  52401. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52402. */
  52403. get: function () {
  52404. return ActionManager._OnEveryFrameTrigger;
  52405. },
  52406. enumerable: true,
  52407. configurable: true
  52408. });
  52409. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52410. /**
  52411. * On intersection enter
  52412. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52413. */
  52414. get: function () {
  52415. return ActionManager._OnIntersectionEnterTrigger;
  52416. },
  52417. enumerable: true,
  52418. configurable: true
  52419. });
  52420. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52421. /**
  52422. * On intersection exit
  52423. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52424. */
  52425. get: function () {
  52426. return ActionManager._OnIntersectionExitTrigger;
  52427. },
  52428. enumerable: true,
  52429. configurable: true
  52430. });
  52431. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52432. /**
  52433. * On key down
  52434. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52435. */
  52436. get: function () {
  52437. return ActionManager._OnKeyDownTrigger;
  52438. },
  52439. enumerable: true,
  52440. configurable: true
  52441. });
  52442. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52443. /**
  52444. * On key up
  52445. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52446. */
  52447. get: function () {
  52448. return ActionManager._OnKeyUpTrigger;
  52449. },
  52450. enumerable: true,
  52451. configurable: true
  52452. });
  52453. // Methods
  52454. /**
  52455. * Releases all associated resources
  52456. */
  52457. ActionManager.prototype.dispose = function () {
  52458. var index = this._scene._actionManagers.indexOf(this);
  52459. for (var i = 0; i < this.actions.length; i++) {
  52460. var action = this.actions[i];
  52461. ActionManager.Triggers[action.trigger]--;
  52462. if (ActionManager.Triggers[action.trigger] === 0) {
  52463. delete ActionManager.Triggers[action.trigger];
  52464. }
  52465. }
  52466. if (index > -1) {
  52467. this._scene._actionManagers.splice(index, 1);
  52468. }
  52469. };
  52470. /**
  52471. * Gets hosting scene
  52472. * @returns the hosting scene
  52473. */
  52474. ActionManager.prototype.getScene = function () {
  52475. return this._scene;
  52476. };
  52477. /**
  52478. * Does this action manager handles actions of any of the given triggers
  52479. * @param triggers defines the triggers to be tested
  52480. * @return a boolean indicating whether one (or more) of the triggers is handled
  52481. */
  52482. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52483. for (var index = 0; index < this.actions.length; index++) {
  52484. var action = this.actions[index];
  52485. if (triggers.indexOf(action.trigger) > -1) {
  52486. return true;
  52487. }
  52488. }
  52489. return false;
  52490. };
  52491. /**
  52492. * Does this action manager handles actions of a given trigger
  52493. * @param trigger defines the trigger to be tested
  52494. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52495. * @return whether the trigger is handled
  52496. */
  52497. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52498. for (var index = 0; index < this.actions.length; index++) {
  52499. var action = this.actions[index];
  52500. if (action.trigger === trigger) {
  52501. if (parameterPredicate) {
  52502. if (parameterPredicate(action.getTriggerParameter())) {
  52503. return true;
  52504. }
  52505. }
  52506. else {
  52507. return true;
  52508. }
  52509. }
  52510. }
  52511. return false;
  52512. };
  52513. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52514. /**
  52515. * Does this action manager has pointer triggers
  52516. */
  52517. get: function () {
  52518. for (var index = 0; index < this.actions.length; index++) {
  52519. var action = this.actions[index];
  52520. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52521. return true;
  52522. }
  52523. }
  52524. return false;
  52525. },
  52526. enumerable: true,
  52527. configurable: true
  52528. });
  52529. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52530. /**
  52531. * Does this action manager has pick triggers
  52532. */
  52533. get: function () {
  52534. for (var index = 0; index < this.actions.length; index++) {
  52535. var action = this.actions[index];
  52536. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52537. return true;
  52538. }
  52539. }
  52540. return false;
  52541. },
  52542. enumerable: true,
  52543. configurable: true
  52544. });
  52545. Object.defineProperty(ActionManager, "HasTriggers", {
  52546. /**
  52547. * Does exist one action manager with at least one trigger
  52548. **/
  52549. get: function () {
  52550. for (var t in ActionManager.Triggers) {
  52551. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52552. return true;
  52553. }
  52554. }
  52555. return false;
  52556. },
  52557. enumerable: true,
  52558. configurable: true
  52559. });
  52560. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52561. /**
  52562. * Does exist one action manager with at least one pick trigger
  52563. **/
  52564. get: function () {
  52565. for (var t in ActionManager.Triggers) {
  52566. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52567. var t_int = parseInt(t);
  52568. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52569. return true;
  52570. }
  52571. }
  52572. }
  52573. return false;
  52574. },
  52575. enumerable: true,
  52576. configurable: true
  52577. });
  52578. /**
  52579. * Does exist one action manager that handles actions of a given trigger
  52580. * @param trigger defines the trigger to be tested
  52581. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52582. **/
  52583. ActionManager.HasSpecificTrigger = function (trigger) {
  52584. for (var t in ActionManager.Triggers) {
  52585. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52586. var t_int = parseInt(t);
  52587. if (t_int === trigger) {
  52588. return true;
  52589. }
  52590. }
  52591. }
  52592. return false;
  52593. };
  52594. /**
  52595. * Registers an action to this action manager
  52596. * @param action defines the action to be registered
  52597. * @return the action amended (prepared) after registration
  52598. */
  52599. ActionManager.prototype.registerAction = function (action) {
  52600. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52601. if (this.getScene().actionManager !== this) {
  52602. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52603. return null;
  52604. }
  52605. }
  52606. this.actions.push(action);
  52607. if (ActionManager.Triggers[action.trigger]) {
  52608. ActionManager.Triggers[action.trigger]++;
  52609. }
  52610. else {
  52611. ActionManager.Triggers[action.trigger] = 1;
  52612. }
  52613. action._actionManager = this;
  52614. action._prepare();
  52615. return action;
  52616. };
  52617. /**
  52618. * Unregisters an action to this action manager
  52619. * @param action defines the action to be unregistered
  52620. * @return a boolean indicating whether the action has been unregistered
  52621. */
  52622. ActionManager.prototype.unregisterAction = function (action) {
  52623. var index = this.actions.indexOf(action);
  52624. if (index !== -1) {
  52625. this.actions.splice(index, 1);
  52626. ActionManager.Triggers[action.trigger] -= 1;
  52627. if (ActionManager.Triggers[action.trigger] === 0) {
  52628. delete ActionManager.Triggers[action.trigger];
  52629. }
  52630. delete action._actionManager;
  52631. return true;
  52632. }
  52633. return false;
  52634. };
  52635. /**
  52636. * Process a specific trigger
  52637. * @param trigger defines the trigger to process
  52638. * @param evt defines the event details to be processed
  52639. */
  52640. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52641. for (var index = 0; index < this.actions.length; index++) {
  52642. var action = this.actions[index];
  52643. if (action.trigger === trigger) {
  52644. if (evt) {
  52645. if (trigger === ActionManager.OnKeyUpTrigger
  52646. || trigger === ActionManager.OnKeyDownTrigger) {
  52647. var parameter = action.getTriggerParameter();
  52648. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52649. if (!parameter.toLowerCase) {
  52650. continue;
  52651. }
  52652. var lowerCase = parameter.toLowerCase();
  52653. if (lowerCase !== evt.sourceEvent.key) {
  52654. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52655. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52656. if (actualkey !== lowerCase) {
  52657. continue;
  52658. }
  52659. }
  52660. }
  52661. }
  52662. }
  52663. action._executeCurrent(evt);
  52664. }
  52665. }
  52666. };
  52667. /** @hidden */
  52668. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52669. var properties = propertyPath.split(".");
  52670. for (var index = 0; index < properties.length - 1; index++) {
  52671. target = target[properties[index]];
  52672. }
  52673. return target;
  52674. };
  52675. /** @hidden */
  52676. ActionManager.prototype._getProperty = function (propertyPath) {
  52677. var properties = propertyPath.split(".");
  52678. return properties[properties.length - 1];
  52679. };
  52680. /**
  52681. * Serialize this manager to a JSON object
  52682. * @param name defines the property name to store this manager
  52683. * @returns a JSON representation of this manager
  52684. */
  52685. ActionManager.prototype.serialize = function (name) {
  52686. var root = {
  52687. children: new Array(),
  52688. name: name,
  52689. type: 3,
  52690. properties: new Array() // Empty for root but required
  52691. };
  52692. for (var i = 0; i < this.actions.length; i++) {
  52693. var triggerObject = {
  52694. type: 0,
  52695. children: new Array(),
  52696. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52697. properties: new Array()
  52698. };
  52699. var triggerOptions = this.actions[i].triggerOptions;
  52700. if (triggerOptions && typeof triggerOptions !== "number") {
  52701. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52702. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52703. }
  52704. else {
  52705. var parameter = {};
  52706. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52707. if (triggerOptions.parameter.mesh) {
  52708. parameter._meshId = triggerOptions.parameter.mesh.id;
  52709. }
  52710. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52711. }
  52712. }
  52713. // Serialize child action, recursively
  52714. this.actions[i].serialize(triggerObject);
  52715. // Add serialized trigger
  52716. root.children.push(triggerObject);
  52717. }
  52718. return root;
  52719. };
  52720. /**
  52721. * Creates a new ActionManager from a JSON data
  52722. * @param parsedActions defines the JSON data to read from
  52723. * @param object defines the hosting mesh
  52724. * @param scene defines the hosting scene
  52725. */
  52726. ActionManager.Parse = function (parsedActions, object, scene) {
  52727. var actionManager = new ActionManager(scene);
  52728. if (object === null)
  52729. scene.actionManager = actionManager;
  52730. else
  52731. object.actionManager = actionManager;
  52732. // instanciate a new object
  52733. var instanciate = function (name, params) {
  52734. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52735. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52736. newInstance.constructor.apply(newInstance, params);
  52737. return newInstance;
  52738. };
  52739. var parseParameter = function (name, value, target, propertyPath) {
  52740. if (propertyPath === null) {
  52741. // String, boolean or float
  52742. var floatValue = parseFloat(value);
  52743. if (value === "true" || value === "false")
  52744. return value === "true";
  52745. else
  52746. return isNaN(floatValue) ? value : floatValue;
  52747. }
  52748. var effectiveTarget = propertyPath.split(".");
  52749. var values = value.split(",");
  52750. // Get effective Target
  52751. for (var i = 0; i < effectiveTarget.length; i++) {
  52752. target = target[effectiveTarget[i]];
  52753. }
  52754. // Return appropriate value with its type
  52755. if (typeof (target) === "boolean")
  52756. return values[0] === "true";
  52757. if (typeof (target) === "string")
  52758. return values[0];
  52759. // Parameters with multiple values such as Vector3 etc.
  52760. var split = new Array();
  52761. for (var i = 0; i < values.length; i++)
  52762. split.push(parseFloat(values[i]));
  52763. if (target instanceof BABYLON.Vector3)
  52764. return BABYLON.Vector3.FromArray(split);
  52765. if (target instanceof BABYLON.Vector4)
  52766. return BABYLON.Vector4.FromArray(split);
  52767. if (target instanceof BABYLON.Color3)
  52768. return BABYLON.Color3.FromArray(split);
  52769. if (target instanceof BABYLON.Color4)
  52770. return BABYLON.Color4.FromArray(split);
  52771. return parseFloat(values[0]);
  52772. };
  52773. // traverse graph per trigger
  52774. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52775. if (combineArray === void 0) { combineArray = null; }
  52776. if (parsedAction.detached)
  52777. return;
  52778. var parameters = new Array();
  52779. var target = null;
  52780. var propertyPath = null;
  52781. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52782. // Parameters
  52783. if (parsedAction.type === 2)
  52784. parameters.push(actionManager);
  52785. else
  52786. parameters.push(trigger);
  52787. if (combine) {
  52788. var actions = new Array();
  52789. for (var j = 0; j < parsedAction.combine.length; j++) {
  52790. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52791. }
  52792. parameters.push(actions);
  52793. }
  52794. else {
  52795. for (var i = 0; i < parsedAction.properties.length; i++) {
  52796. var value = parsedAction.properties[i].value;
  52797. var name = parsedAction.properties[i].name;
  52798. var targetType = parsedAction.properties[i].targetType;
  52799. if (name === "target")
  52800. if (targetType !== null && targetType === "SceneProperties")
  52801. value = target = scene;
  52802. else
  52803. value = target = scene.getNodeByName(value);
  52804. else if (name === "parent")
  52805. value = scene.getNodeByName(value);
  52806. else if (name === "sound")
  52807. value = scene.getSoundByName(value);
  52808. else if (name !== "propertyPath") {
  52809. if (parsedAction.type === 2 && name === "operator")
  52810. value = BABYLON.ValueCondition[value];
  52811. else
  52812. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52813. }
  52814. else {
  52815. propertyPath = value;
  52816. }
  52817. parameters.push(value);
  52818. }
  52819. }
  52820. if (combineArray === null) {
  52821. parameters.push(condition);
  52822. }
  52823. else {
  52824. parameters.push(null);
  52825. }
  52826. // If interpolate value action
  52827. if (parsedAction.name === "InterpolateValueAction") {
  52828. var param = parameters[parameters.length - 2];
  52829. parameters[parameters.length - 1] = param;
  52830. parameters[parameters.length - 2] = condition;
  52831. }
  52832. // Action or condition(s) and not CombineAction
  52833. var newAction = instanciate(parsedAction.name, parameters);
  52834. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52835. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52836. if (action)
  52837. action.then(nothing);
  52838. else
  52839. actionManager.registerAction(nothing);
  52840. action = nothing;
  52841. }
  52842. if (combineArray === null) {
  52843. if (newAction instanceof BABYLON.Condition) {
  52844. condition = newAction;
  52845. newAction = action;
  52846. }
  52847. else {
  52848. condition = null;
  52849. if (action)
  52850. action.then(newAction);
  52851. else
  52852. actionManager.registerAction(newAction);
  52853. }
  52854. }
  52855. else {
  52856. combineArray.push(newAction);
  52857. }
  52858. for (var i = 0; i < parsedAction.children.length; i++)
  52859. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  52860. };
  52861. // triggers
  52862. for (var i = 0; i < parsedActions.children.length; i++) {
  52863. var triggerParams;
  52864. var trigger = parsedActions.children[i];
  52865. if (trigger.properties.length > 0) {
  52866. var param = trigger.properties[0].value;
  52867. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  52868. if (value._meshId) {
  52869. value.mesh = scene.getMeshByID(value._meshId);
  52870. }
  52871. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  52872. }
  52873. else
  52874. triggerParams = ActionManager[trigger.name];
  52875. for (var j = 0; j < trigger.children.length; j++) {
  52876. if (!trigger.detached)
  52877. traverse(trigger.children[j], triggerParams, null, null);
  52878. }
  52879. }
  52880. };
  52881. /**
  52882. * Get a trigger name by index
  52883. * @param trigger defines the trigger index
  52884. * @returns a trigger name
  52885. */
  52886. ActionManager.GetTriggerName = function (trigger) {
  52887. switch (trigger) {
  52888. case 0: return "NothingTrigger";
  52889. case 1: return "OnPickTrigger";
  52890. case 2: return "OnLeftPickTrigger";
  52891. case 3: return "OnRightPickTrigger";
  52892. case 4: return "OnCenterPickTrigger";
  52893. case 5: return "OnPickDownTrigger";
  52894. case 6: return "OnPickUpTrigger";
  52895. case 7: return "OnLongPressTrigger";
  52896. case 8: return "OnPointerOverTrigger";
  52897. case 9: return "OnPointerOutTrigger";
  52898. case 10: return "OnEveryFrameTrigger";
  52899. case 11: return "OnIntersectionEnterTrigger";
  52900. case 12: return "OnIntersectionExitTrigger";
  52901. case 13: return "OnKeyDownTrigger";
  52902. case 14: return "OnKeyUpTrigger";
  52903. case 15: return "OnPickOutTrigger";
  52904. default: return "";
  52905. }
  52906. };
  52907. // Statics
  52908. ActionManager._NothingTrigger = 0;
  52909. ActionManager._OnPickTrigger = 1;
  52910. ActionManager._OnLeftPickTrigger = 2;
  52911. ActionManager._OnRightPickTrigger = 3;
  52912. ActionManager._OnCenterPickTrigger = 4;
  52913. ActionManager._OnPickDownTrigger = 5;
  52914. ActionManager._OnDoublePickTrigger = 6;
  52915. ActionManager._OnPickUpTrigger = 7;
  52916. ActionManager._OnLongPressTrigger = 8;
  52917. ActionManager._OnPointerOverTrigger = 9;
  52918. ActionManager._OnPointerOutTrigger = 10;
  52919. ActionManager._OnEveryFrameTrigger = 11;
  52920. ActionManager._OnIntersectionEnterTrigger = 12;
  52921. ActionManager._OnIntersectionExitTrigger = 13;
  52922. ActionManager._OnKeyDownTrigger = 14;
  52923. ActionManager._OnKeyUpTrigger = 15;
  52924. ActionManager._OnPickOutTrigger = 16;
  52925. /** Gets the list of active triggers */
  52926. ActionManager.Triggers = {};
  52927. return ActionManager;
  52928. }());
  52929. BABYLON.ActionManager = ActionManager;
  52930. })(BABYLON || (BABYLON = {}));
  52931. //# sourceMappingURL=babylon.actionManager.js.map
  52932. var BABYLON;
  52933. (function (BABYLON) {
  52934. var InterpolateValueAction = /** @class */ (function (_super) {
  52935. __extends(InterpolateValueAction, _super);
  52936. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  52937. if (duration === void 0) { duration = 1000; }
  52938. var _this = _super.call(this, triggerOptions, condition) || this;
  52939. _this.propertyPath = propertyPath;
  52940. _this.value = value;
  52941. _this.duration = duration;
  52942. _this.stopOtherAnimations = stopOtherAnimations;
  52943. _this.onInterpolationDone = onInterpolationDone;
  52944. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  52945. _this._target = _this._effectiveTarget = target;
  52946. return _this;
  52947. }
  52948. InterpolateValueAction.prototype._prepare = function () {
  52949. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52950. this._property = this._getProperty(this.propertyPath);
  52951. };
  52952. InterpolateValueAction.prototype.execute = function () {
  52953. var _this = this;
  52954. var scene = this._actionManager.getScene();
  52955. var keys = [
  52956. {
  52957. frame: 0,
  52958. value: this._effectiveTarget[this._property]
  52959. }, {
  52960. frame: 100,
  52961. value: this.value
  52962. }
  52963. ];
  52964. var dataType;
  52965. if (typeof this.value === "number") {
  52966. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  52967. }
  52968. else if (this.value instanceof BABYLON.Color3) {
  52969. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  52970. }
  52971. else if (this.value instanceof BABYLON.Vector3) {
  52972. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  52973. }
  52974. else if (this.value instanceof BABYLON.Matrix) {
  52975. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  52976. }
  52977. else if (this.value instanceof BABYLON.Quaternion) {
  52978. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  52979. }
  52980. else {
  52981. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  52982. return;
  52983. }
  52984. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  52985. animation.setKeys(keys);
  52986. if (this.stopOtherAnimations) {
  52987. scene.stopAnimation(this._effectiveTarget);
  52988. }
  52989. var wrapper = function () {
  52990. _this.onInterpolationDoneObservable.notifyObservers(_this);
  52991. if (_this.onInterpolationDone) {
  52992. _this.onInterpolationDone();
  52993. }
  52994. };
  52995. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  52996. };
  52997. InterpolateValueAction.prototype.serialize = function (parent) {
  52998. return _super.prototype._serialize.call(this, {
  52999. name: "InterpolateValueAction",
  53000. properties: [
  53001. BABYLON.Action._GetTargetProperty(this._target),
  53002. { name: "propertyPath", value: this.propertyPath },
  53003. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53004. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53005. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53006. ]
  53007. }, parent);
  53008. };
  53009. return InterpolateValueAction;
  53010. }(BABYLON.Action));
  53011. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53012. })(BABYLON || (BABYLON = {}));
  53013. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53014. var BABYLON;
  53015. (function (BABYLON) {
  53016. var SwitchBooleanAction = /** @class */ (function (_super) {
  53017. __extends(SwitchBooleanAction, _super);
  53018. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53019. var _this = _super.call(this, triggerOptions, condition) || this;
  53020. _this.propertyPath = propertyPath;
  53021. _this._target = _this._effectiveTarget = target;
  53022. return _this;
  53023. }
  53024. SwitchBooleanAction.prototype._prepare = function () {
  53025. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53026. this._property = this._getProperty(this.propertyPath);
  53027. };
  53028. SwitchBooleanAction.prototype.execute = function () {
  53029. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53030. };
  53031. SwitchBooleanAction.prototype.serialize = function (parent) {
  53032. return _super.prototype._serialize.call(this, {
  53033. name: "SwitchBooleanAction",
  53034. properties: [
  53035. BABYLON.Action._GetTargetProperty(this._target),
  53036. { name: "propertyPath", value: this.propertyPath }
  53037. ]
  53038. }, parent);
  53039. };
  53040. return SwitchBooleanAction;
  53041. }(BABYLON.Action));
  53042. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53043. var SetStateAction = /** @class */ (function (_super) {
  53044. __extends(SetStateAction, _super);
  53045. function SetStateAction(triggerOptions, target, value, condition) {
  53046. var _this = _super.call(this, triggerOptions, condition) || this;
  53047. _this.value = value;
  53048. _this._target = target;
  53049. return _this;
  53050. }
  53051. SetStateAction.prototype.execute = function () {
  53052. this._target.state = this.value;
  53053. };
  53054. SetStateAction.prototype.serialize = function (parent) {
  53055. return _super.prototype._serialize.call(this, {
  53056. name: "SetStateAction",
  53057. properties: [
  53058. BABYLON.Action._GetTargetProperty(this._target),
  53059. { name: "value", value: this.value }
  53060. ]
  53061. }, parent);
  53062. };
  53063. return SetStateAction;
  53064. }(BABYLON.Action));
  53065. BABYLON.SetStateAction = SetStateAction;
  53066. var SetValueAction = /** @class */ (function (_super) {
  53067. __extends(SetValueAction, _super);
  53068. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53069. var _this = _super.call(this, triggerOptions, condition) || this;
  53070. _this.propertyPath = propertyPath;
  53071. _this.value = value;
  53072. _this._target = _this._effectiveTarget = target;
  53073. return _this;
  53074. }
  53075. SetValueAction.prototype._prepare = function () {
  53076. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53077. this._property = this._getProperty(this.propertyPath);
  53078. };
  53079. SetValueAction.prototype.execute = function () {
  53080. this._effectiveTarget[this._property] = this.value;
  53081. if (this._target.markAsDirty) {
  53082. this._target.markAsDirty(this._property);
  53083. }
  53084. };
  53085. SetValueAction.prototype.serialize = function (parent) {
  53086. return _super.prototype._serialize.call(this, {
  53087. name: "SetValueAction",
  53088. properties: [
  53089. BABYLON.Action._GetTargetProperty(this._target),
  53090. { name: "propertyPath", value: this.propertyPath },
  53091. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53092. ]
  53093. }, parent);
  53094. };
  53095. return SetValueAction;
  53096. }(BABYLON.Action));
  53097. BABYLON.SetValueAction = SetValueAction;
  53098. var IncrementValueAction = /** @class */ (function (_super) {
  53099. __extends(IncrementValueAction, _super);
  53100. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53101. var _this = _super.call(this, triggerOptions, condition) || this;
  53102. _this.propertyPath = propertyPath;
  53103. _this.value = value;
  53104. _this._target = _this._effectiveTarget = target;
  53105. return _this;
  53106. }
  53107. IncrementValueAction.prototype._prepare = function () {
  53108. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53109. this._property = this._getProperty(this.propertyPath);
  53110. if (typeof this._effectiveTarget[this._property] !== "number") {
  53111. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53112. }
  53113. };
  53114. IncrementValueAction.prototype.execute = function () {
  53115. this._effectiveTarget[this._property] += this.value;
  53116. if (this._target.markAsDirty) {
  53117. this._target.markAsDirty(this._property);
  53118. }
  53119. };
  53120. IncrementValueAction.prototype.serialize = function (parent) {
  53121. return _super.prototype._serialize.call(this, {
  53122. name: "IncrementValueAction",
  53123. properties: [
  53124. BABYLON.Action._GetTargetProperty(this._target),
  53125. { name: "propertyPath", value: this.propertyPath },
  53126. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53127. ]
  53128. }, parent);
  53129. };
  53130. return IncrementValueAction;
  53131. }(BABYLON.Action));
  53132. BABYLON.IncrementValueAction = IncrementValueAction;
  53133. var PlayAnimationAction = /** @class */ (function (_super) {
  53134. __extends(PlayAnimationAction, _super);
  53135. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53136. var _this = _super.call(this, triggerOptions, condition) || this;
  53137. _this.from = from;
  53138. _this.to = to;
  53139. _this.loop = loop;
  53140. _this._target = target;
  53141. return _this;
  53142. }
  53143. PlayAnimationAction.prototype._prepare = function () {
  53144. };
  53145. PlayAnimationAction.prototype.execute = function () {
  53146. var scene = this._actionManager.getScene();
  53147. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53148. };
  53149. PlayAnimationAction.prototype.serialize = function (parent) {
  53150. return _super.prototype._serialize.call(this, {
  53151. name: "PlayAnimationAction",
  53152. properties: [
  53153. BABYLON.Action._GetTargetProperty(this._target),
  53154. { name: "from", value: String(this.from) },
  53155. { name: "to", value: String(this.to) },
  53156. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53157. ]
  53158. }, parent);
  53159. };
  53160. return PlayAnimationAction;
  53161. }(BABYLON.Action));
  53162. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53163. var StopAnimationAction = /** @class */ (function (_super) {
  53164. __extends(StopAnimationAction, _super);
  53165. function StopAnimationAction(triggerOptions, target, condition) {
  53166. var _this = _super.call(this, triggerOptions, condition) || this;
  53167. _this._target = target;
  53168. return _this;
  53169. }
  53170. StopAnimationAction.prototype._prepare = function () {
  53171. };
  53172. StopAnimationAction.prototype.execute = function () {
  53173. var scene = this._actionManager.getScene();
  53174. scene.stopAnimation(this._target);
  53175. };
  53176. StopAnimationAction.prototype.serialize = function (parent) {
  53177. return _super.prototype._serialize.call(this, {
  53178. name: "StopAnimationAction",
  53179. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53180. }, parent);
  53181. };
  53182. return StopAnimationAction;
  53183. }(BABYLON.Action));
  53184. BABYLON.StopAnimationAction = StopAnimationAction;
  53185. var DoNothingAction = /** @class */ (function (_super) {
  53186. __extends(DoNothingAction, _super);
  53187. function DoNothingAction(triggerOptions, condition) {
  53188. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53189. return _super.call(this, triggerOptions, condition) || this;
  53190. }
  53191. DoNothingAction.prototype.execute = function () {
  53192. };
  53193. DoNothingAction.prototype.serialize = function (parent) {
  53194. return _super.prototype._serialize.call(this, {
  53195. name: "DoNothingAction",
  53196. properties: []
  53197. }, parent);
  53198. };
  53199. return DoNothingAction;
  53200. }(BABYLON.Action));
  53201. BABYLON.DoNothingAction = DoNothingAction;
  53202. var CombineAction = /** @class */ (function (_super) {
  53203. __extends(CombineAction, _super);
  53204. function CombineAction(triggerOptions, children, condition) {
  53205. var _this = _super.call(this, triggerOptions, condition) || this;
  53206. _this.children = children;
  53207. return _this;
  53208. }
  53209. CombineAction.prototype._prepare = function () {
  53210. for (var index = 0; index < this.children.length; index++) {
  53211. this.children[index]._actionManager = this._actionManager;
  53212. this.children[index]._prepare();
  53213. }
  53214. };
  53215. CombineAction.prototype.execute = function (evt) {
  53216. for (var index = 0; index < this.children.length; index++) {
  53217. this.children[index].execute(evt);
  53218. }
  53219. };
  53220. CombineAction.prototype.serialize = function (parent) {
  53221. var serializationObject = _super.prototype._serialize.call(this, {
  53222. name: "CombineAction",
  53223. properties: [],
  53224. combine: []
  53225. }, parent);
  53226. for (var i = 0; i < this.children.length; i++) {
  53227. serializationObject.combine.push(this.children[i].serialize(null));
  53228. }
  53229. return serializationObject;
  53230. };
  53231. return CombineAction;
  53232. }(BABYLON.Action));
  53233. BABYLON.CombineAction = CombineAction;
  53234. var ExecuteCodeAction = /** @class */ (function (_super) {
  53235. __extends(ExecuteCodeAction, _super);
  53236. function ExecuteCodeAction(triggerOptions, func, condition) {
  53237. var _this = _super.call(this, triggerOptions, condition) || this;
  53238. _this.func = func;
  53239. return _this;
  53240. }
  53241. ExecuteCodeAction.prototype.execute = function (evt) {
  53242. this.func(evt);
  53243. };
  53244. return ExecuteCodeAction;
  53245. }(BABYLON.Action));
  53246. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53247. var SetParentAction = /** @class */ (function (_super) {
  53248. __extends(SetParentAction, _super);
  53249. function SetParentAction(triggerOptions, target, parent, condition) {
  53250. var _this = _super.call(this, triggerOptions, condition) || this;
  53251. _this._target = target;
  53252. _this._parent = parent;
  53253. return _this;
  53254. }
  53255. SetParentAction.prototype._prepare = function () {
  53256. };
  53257. SetParentAction.prototype.execute = function () {
  53258. if (this._target.parent === this._parent) {
  53259. return;
  53260. }
  53261. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53262. invertParentWorldMatrix.invert();
  53263. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53264. this._target.parent = this._parent;
  53265. };
  53266. SetParentAction.prototype.serialize = function (parent) {
  53267. return _super.prototype._serialize.call(this, {
  53268. name: "SetParentAction",
  53269. properties: [
  53270. BABYLON.Action._GetTargetProperty(this._target),
  53271. BABYLON.Action._GetTargetProperty(this._parent),
  53272. ]
  53273. }, parent);
  53274. };
  53275. return SetParentAction;
  53276. }(BABYLON.Action));
  53277. BABYLON.SetParentAction = SetParentAction;
  53278. var PlaySoundAction = /** @class */ (function (_super) {
  53279. __extends(PlaySoundAction, _super);
  53280. function PlaySoundAction(triggerOptions, sound, condition) {
  53281. var _this = _super.call(this, triggerOptions, condition) || this;
  53282. _this._sound = sound;
  53283. return _this;
  53284. }
  53285. PlaySoundAction.prototype._prepare = function () {
  53286. };
  53287. PlaySoundAction.prototype.execute = function () {
  53288. if (this._sound !== undefined)
  53289. this._sound.play();
  53290. };
  53291. PlaySoundAction.prototype.serialize = function (parent) {
  53292. return _super.prototype._serialize.call(this, {
  53293. name: "PlaySoundAction",
  53294. properties: [{ name: "sound", value: this._sound.name }]
  53295. }, parent);
  53296. };
  53297. return PlaySoundAction;
  53298. }(BABYLON.Action));
  53299. BABYLON.PlaySoundAction = PlaySoundAction;
  53300. var StopSoundAction = /** @class */ (function (_super) {
  53301. __extends(StopSoundAction, _super);
  53302. function StopSoundAction(triggerOptions, sound, condition) {
  53303. var _this = _super.call(this, triggerOptions, condition) || this;
  53304. _this._sound = sound;
  53305. return _this;
  53306. }
  53307. StopSoundAction.prototype._prepare = function () {
  53308. };
  53309. StopSoundAction.prototype.execute = function () {
  53310. if (this._sound !== undefined)
  53311. this._sound.stop();
  53312. };
  53313. StopSoundAction.prototype.serialize = function (parent) {
  53314. return _super.prototype._serialize.call(this, {
  53315. name: "StopSoundAction",
  53316. properties: [{ name: "sound", value: this._sound.name }]
  53317. }, parent);
  53318. };
  53319. return StopSoundAction;
  53320. }(BABYLON.Action));
  53321. BABYLON.StopSoundAction = StopSoundAction;
  53322. })(BABYLON || (BABYLON = {}));
  53323. //# sourceMappingURL=babylon.directActions.js.map
  53324. var BABYLON;
  53325. (function (BABYLON) {
  53326. var SpriteManager = /** @class */ (function () {
  53327. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53328. if (epsilon === void 0) { epsilon = 0.01; }
  53329. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53330. this.name = name;
  53331. this.sprites = new Array();
  53332. this.renderingGroupId = 0;
  53333. this.layerMask = 0x0FFFFFFF;
  53334. this.fogEnabled = true;
  53335. this.isPickable = false;
  53336. /**
  53337. * An event triggered when the manager is disposed.
  53338. */
  53339. this.onDisposeObservable = new BABYLON.Observable();
  53340. this._vertexBuffers = {};
  53341. this._capacity = capacity;
  53342. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53343. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53344. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53345. if (cellSize.width && cellSize.height) {
  53346. this.cellWidth = cellSize.width;
  53347. this.cellHeight = cellSize.height;
  53348. }
  53349. else if (cellSize !== undefined) {
  53350. this.cellWidth = cellSize;
  53351. this.cellHeight = cellSize;
  53352. }
  53353. else {
  53354. return;
  53355. }
  53356. this._epsilon = epsilon;
  53357. this._scene = scene;
  53358. this._scene.spriteManagers.push(this);
  53359. var indices = [];
  53360. var index = 0;
  53361. for (var count = 0; count < capacity; count++) {
  53362. indices.push(index);
  53363. indices.push(index + 1);
  53364. indices.push(index + 2);
  53365. indices.push(index);
  53366. indices.push(index + 2);
  53367. indices.push(index + 3);
  53368. index += 4;
  53369. }
  53370. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53371. // VBO
  53372. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53373. this._vertexData = new Float32Array(capacity * 16 * 4);
  53374. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53375. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53376. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53377. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53378. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53379. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53380. this._vertexBuffers["options"] = options;
  53381. this._vertexBuffers["cellInfo"] = cellInfo;
  53382. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53383. // Effects
  53384. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53385. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53386. }
  53387. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53388. set: function (callback) {
  53389. if (this._onDisposeObserver) {
  53390. this.onDisposeObservable.remove(this._onDisposeObserver);
  53391. }
  53392. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53393. },
  53394. enumerable: true,
  53395. configurable: true
  53396. });
  53397. Object.defineProperty(SpriteManager.prototype, "texture", {
  53398. get: function () {
  53399. return this._spriteTexture;
  53400. },
  53401. set: function (value) {
  53402. this._spriteTexture = value;
  53403. },
  53404. enumerable: true,
  53405. configurable: true
  53406. });
  53407. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53408. var arrayOffset = index * 16;
  53409. if (offsetX === 0)
  53410. offsetX = this._epsilon;
  53411. else if (offsetX === 1)
  53412. offsetX = 1 - this._epsilon;
  53413. if (offsetY === 0)
  53414. offsetY = this._epsilon;
  53415. else if (offsetY === 1)
  53416. offsetY = 1 - this._epsilon;
  53417. this._vertexData[arrayOffset] = sprite.position.x;
  53418. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53419. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53420. this._vertexData[arrayOffset + 3] = sprite.angle;
  53421. this._vertexData[arrayOffset + 4] = sprite.width;
  53422. this._vertexData[arrayOffset + 5] = sprite.height;
  53423. this._vertexData[arrayOffset + 6] = offsetX;
  53424. this._vertexData[arrayOffset + 7] = offsetY;
  53425. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53426. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53427. var offset = (sprite.cellIndex / rowSize) >> 0;
  53428. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53429. this._vertexData[arrayOffset + 11] = offset;
  53430. // Color
  53431. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53432. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53433. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53434. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53435. };
  53436. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53437. var count = Math.min(this._capacity, this.sprites.length);
  53438. var min = BABYLON.Vector3.Zero();
  53439. var max = BABYLON.Vector3.Zero();
  53440. var distance = Number.MAX_VALUE;
  53441. var currentSprite = null;
  53442. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53443. var cameraView = camera.getViewMatrix();
  53444. for (var index = 0; index < count; index++) {
  53445. var sprite = this.sprites[index];
  53446. if (!sprite) {
  53447. continue;
  53448. }
  53449. if (predicate) {
  53450. if (!predicate(sprite)) {
  53451. continue;
  53452. }
  53453. }
  53454. else if (!sprite.isPickable) {
  53455. continue;
  53456. }
  53457. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53458. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53459. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53460. if (ray.intersectsBoxMinMax(min, max)) {
  53461. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53462. if (distance > currentDistance) {
  53463. distance = currentDistance;
  53464. currentSprite = sprite;
  53465. if (fastCheck) {
  53466. break;
  53467. }
  53468. }
  53469. }
  53470. }
  53471. if (currentSprite) {
  53472. var result = new BABYLON.PickingInfo();
  53473. result.hit = true;
  53474. result.pickedSprite = currentSprite;
  53475. result.distance = distance;
  53476. return result;
  53477. }
  53478. return null;
  53479. };
  53480. SpriteManager.prototype.render = function () {
  53481. // Check
  53482. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53483. return;
  53484. var engine = this._scene.getEngine();
  53485. var baseSize = this._spriteTexture.getBaseSize();
  53486. // Sprites
  53487. var deltaTime = engine.getDeltaTime();
  53488. var max = Math.min(this._capacity, this.sprites.length);
  53489. var rowSize = baseSize.width / this.cellWidth;
  53490. var offset = 0;
  53491. for (var index = 0; index < max; index++) {
  53492. var sprite = this.sprites[index];
  53493. if (!sprite || !sprite.isVisible) {
  53494. continue;
  53495. }
  53496. sprite._animate(deltaTime);
  53497. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53498. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53499. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53500. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53501. }
  53502. this._buffer.update(this._vertexData);
  53503. // Render
  53504. var effect = this._effectBase;
  53505. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53506. effect = this._effectFog;
  53507. }
  53508. engine.enableEffect(effect);
  53509. var viewMatrix = this._scene.getViewMatrix();
  53510. effect.setTexture("diffuseSampler", this._spriteTexture);
  53511. effect.setMatrix("view", viewMatrix);
  53512. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53513. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53514. // Fog
  53515. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53516. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53517. effect.setColor3("vFogColor", this._scene.fogColor);
  53518. }
  53519. // VBOs
  53520. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53521. // Draw order
  53522. engine.setDepthFunctionToLessOrEqual();
  53523. effect.setBool("alphaTest", true);
  53524. engine.setColorWrite(false);
  53525. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53526. engine.setColorWrite(true);
  53527. effect.setBool("alphaTest", false);
  53528. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53529. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53530. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53531. };
  53532. SpriteManager.prototype.dispose = function () {
  53533. if (this._buffer) {
  53534. this._buffer.dispose();
  53535. this._buffer = null;
  53536. }
  53537. if (this._indexBuffer) {
  53538. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53539. this._indexBuffer = null;
  53540. }
  53541. if (this._spriteTexture) {
  53542. this._spriteTexture.dispose();
  53543. this._spriteTexture = null;
  53544. }
  53545. // Remove from scene
  53546. var index = this._scene.spriteManagers.indexOf(this);
  53547. this._scene.spriteManagers.splice(index, 1);
  53548. // Callback
  53549. this.onDisposeObservable.notifyObservers(this);
  53550. this.onDisposeObservable.clear();
  53551. };
  53552. return SpriteManager;
  53553. }());
  53554. BABYLON.SpriteManager = SpriteManager;
  53555. })(BABYLON || (BABYLON = {}));
  53556. //# sourceMappingURL=babylon.spriteManager.js.map
  53557. var BABYLON;
  53558. (function (BABYLON) {
  53559. var Sprite = /** @class */ (function () {
  53560. function Sprite(name, manager) {
  53561. this.name = name;
  53562. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53563. this.width = 1.0;
  53564. this.height = 1.0;
  53565. this.angle = 0;
  53566. this.cellIndex = 0;
  53567. this.invertU = 0;
  53568. this.invertV = 0;
  53569. this.animations = new Array();
  53570. this.isPickable = false;
  53571. this._animationStarted = false;
  53572. this._loopAnimation = false;
  53573. this._fromIndex = 0;
  53574. this._toIndex = 0;
  53575. this._delay = 0;
  53576. this._direction = 1;
  53577. this._time = 0;
  53578. /**
  53579. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53580. */
  53581. this.isVisible = true;
  53582. this._manager = manager;
  53583. this._manager.sprites.push(this);
  53584. this.position = BABYLON.Vector3.Zero();
  53585. }
  53586. Object.defineProperty(Sprite.prototype, "size", {
  53587. get: function () {
  53588. return this.width;
  53589. },
  53590. set: function (value) {
  53591. this.width = value;
  53592. this.height = value;
  53593. },
  53594. enumerable: true,
  53595. configurable: true
  53596. });
  53597. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53598. this._fromIndex = from;
  53599. this._toIndex = to;
  53600. this._loopAnimation = loop;
  53601. this._delay = delay;
  53602. this._animationStarted = true;
  53603. this._direction = from < to ? 1 : -1;
  53604. this.cellIndex = from;
  53605. this._time = 0;
  53606. this._onAnimationEnd = onAnimationEnd;
  53607. };
  53608. Sprite.prototype.stopAnimation = function () {
  53609. this._animationStarted = false;
  53610. };
  53611. Sprite.prototype._animate = function (deltaTime) {
  53612. if (!this._animationStarted)
  53613. return;
  53614. this._time += deltaTime;
  53615. if (this._time > this._delay) {
  53616. this._time = this._time % this._delay;
  53617. this.cellIndex += this._direction;
  53618. if (this.cellIndex > this._toIndex) {
  53619. if (this._loopAnimation) {
  53620. this.cellIndex = this._fromIndex;
  53621. }
  53622. else {
  53623. this.cellIndex = this._toIndex;
  53624. this._animationStarted = false;
  53625. if (this._onAnimationEnd) {
  53626. this._onAnimationEnd();
  53627. }
  53628. if (this.disposeWhenFinishedAnimating) {
  53629. this.dispose();
  53630. }
  53631. }
  53632. }
  53633. }
  53634. };
  53635. Sprite.prototype.dispose = function () {
  53636. for (var i = 0; i < this._manager.sprites.length; i++) {
  53637. if (this._manager.sprites[i] == this) {
  53638. this._manager.sprites.splice(i, 1);
  53639. }
  53640. }
  53641. };
  53642. return Sprite;
  53643. }());
  53644. BABYLON.Sprite = Sprite;
  53645. })(BABYLON || (BABYLON = {}));
  53646. //# sourceMappingURL=babylon.sprite.js.map
  53647. var BABYLON;
  53648. (function (BABYLON) {
  53649. var IntersectionInfo = /** @class */ (function () {
  53650. function IntersectionInfo(bu, bv, distance) {
  53651. this.bu = bu;
  53652. this.bv = bv;
  53653. this.distance = distance;
  53654. this.faceId = 0;
  53655. this.subMeshId = 0;
  53656. }
  53657. return IntersectionInfo;
  53658. }());
  53659. BABYLON.IntersectionInfo = IntersectionInfo;
  53660. /**
  53661. * Information about the result of picking within a scene
  53662. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53663. */
  53664. var PickingInfo = /** @class */ (function () {
  53665. function PickingInfo() {
  53666. /**
  53667. * If the pick collided with an object
  53668. */
  53669. this.hit = false;
  53670. /**
  53671. * Distance away where the pick collided
  53672. */
  53673. this.distance = 0;
  53674. /**
  53675. * The location of pick collision
  53676. */
  53677. this.pickedPoint = null;
  53678. /**
  53679. * The mesh corrisponding the the pick collision
  53680. */
  53681. this.pickedMesh = null;
  53682. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53683. this.bu = 0;
  53684. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53685. this.bv = 0;
  53686. /** The id of the face on the mesh that was picked */
  53687. this.faceId = -1;
  53688. /** Id of the the submesh that was picked */
  53689. this.subMeshId = 0;
  53690. /** If a sprite was picked, this will be the sprite the pick collided with */
  53691. this.pickedSprite = null;
  53692. /**
  53693. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53694. */
  53695. this.originMesh = null;
  53696. /**
  53697. * The ray that was used to perform the picking.
  53698. */
  53699. this.ray = null;
  53700. }
  53701. /**
  53702. * Gets the normal corrispodning to the face the pick collided with
  53703. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53704. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53705. * @returns The normal corrispodning to the face the pick collided with
  53706. */
  53707. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53708. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53709. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53710. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53711. return null;
  53712. }
  53713. var indices = this.pickedMesh.getIndices();
  53714. if (!indices) {
  53715. return null;
  53716. }
  53717. var result;
  53718. if (useVerticesNormals) {
  53719. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53720. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53721. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53722. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53723. normal0 = normal0.scale(this.bu);
  53724. normal1 = normal1.scale(this.bv);
  53725. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53726. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53727. }
  53728. else {
  53729. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53730. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53731. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53732. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53733. var p1p2 = vertex1.subtract(vertex2);
  53734. var p3p2 = vertex3.subtract(vertex2);
  53735. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53736. }
  53737. if (useWorldCoordinates) {
  53738. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  53739. }
  53740. return BABYLON.Vector3.Normalize(result);
  53741. };
  53742. /**
  53743. * Gets the texture coordinates of where the pick occured
  53744. * @returns the vector containing the coordnates of the texture
  53745. */
  53746. PickingInfo.prototype.getTextureCoordinates = function () {
  53747. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53748. return null;
  53749. }
  53750. var indices = this.pickedMesh.getIndices();
  53751. if (!indices) {
  53752. return null;
  53753. }
  53754. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53755. if (!uvs) {
  53756. return null;
  53757. }
  53758. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53759. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53760. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53761. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53762. uv1 = uv1.scale(this.bu);
  53763. uv2 = uv2.scale(this.bv);
  53764. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53765. };
  53766. return PickingInfo;
  53767. }());
  53768. BABYLON.PickingInfo = PickingInfo;
  53769. })(BABYLON || (BABYLON = {}));
  53770. //# sourceMappingURL=babylon.pickingInfo.js.map
  53771. var BABYLON;
  53772. (function (BABYLON) {
  53773. var Ray = /** @class */ (function () {
  53774. function Ray(origin, direction, length) {
  53775. if (length === void 0) { length = Number.MAX_VALUE; }
  53776. this.origin = origin;
  53777. this.direction = direction;
  53778. this.length = length;
  53779. }
  53780. // Methods
  53781. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53782. var d = 0.0;
  53783. var maxValue = Number.MAX_VALUE;
  53784. var inv;
  53785. var min;
  53786. var max;
  53787. var temp;
  53788. if (Math.abs(this.direction.x) < 0.0000001) {
  53789. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53790. return false;
  53791. }
  53792. }
  53793. else {
  53794. inv = 1.0 / this.direction.x;
  53795. min = (minimum.x - this.origin.x) * inv;
  53796. max = (maximum.x - this.origin.x) * inv;
  53797. if (max === -Infinity) {
  53798. max = Infinity;
  53799. }
  53800. if (min > max) {
  53801. temp = min;
  53802. min = max;
  53803. max = temp;
  53804. }
  53805. d = Math.max(min, d);
  53806. maxValue = Math.min(max, maxValue);
  53807. if (d > maxValue) {
  53808. return false;
  53809. }
  53810. }
  53811. if (Math.abs(this.direction.y) < 0.0000001) {
  53812. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53813. return false;
  53814. }
  53815. }
  53816. else {
  53817. inv = 1.0 / this.direction.y;
  53818. min = (minimum.y - this.origin.y) * inv;
  53819. max = (maximum.y - this.origin.y) * inv;
  53820. if (max === -Infinity) {
  53821. max = Infinity;
  53822. }
  53823. if (min > max) {
  53824. temp = min;
  53825. min = max;
  53826. max = temp;
  53827. }
  53828. d = Math.max(min, d);
  53829. maxValue = Math.min(max, maxValue);
  53830. if (d > maxValue) {
  53831. return false;
  53832. }
  53833. }
  53834. if (Math.abs(this.direction.z) < 0.0000001) {
  53835. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53836. return false;
  53837. }
  53838. }
  53839. else {
  53840. inv = 1.0 / this.direction.z;
  53841. min = (minimum.z - this.origin.z) * inv;
  53842. max = (maximum.z - this.origin.z) * inv;
  53843. if (max === -Infinity) {
  53844. max = Infinity;
  53845. }
  53846. if (min > max) {
  53847. temp = min;
  53848. min = max;
  53849. max = temp;
  53850. }
  53851. d = Math.max(min, d);
  53852. maxValue = Math.min(max, maxValue);
  53853. if (d > maxValue) {
  53854. return false;
  53855. }
  53856. }
  53857. return true;
  53858. };
  53859. Ray.prototype.intersectsBox = function (box) {
  53860. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  53861. };
  53862. Ray.prototype.intersectsSphere = function (sphere) {
  53863. var x = sphere.center.x - this.origin.x;
  53864. var y = sphere.center.y - this.origin.y;
  53865. var z = sphere.center.z - this.origin.z;
  53866. var pyth = (x * x) + (y * y) + (z * z);
  53867. var rr = sphere.radius * sphere.radius;
  53868. if (pyth <= rr) {
  53869. return true;
  53870. }
  53871. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  53872. if (dot < 0.0) {
  53873. return false;
  53874. }
  53875. var temp = pyth - (dot * dot);
  53876. return temp <= rr;
  53877. };
  53878. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  53879. if (!this._edge1) {
  53880. this._edge1 = BABYLON.Vector3.Zero();
  53881. this._edge2 = BABYLON.Vector3.Zero();
  53882. this._pvec = BABYLON.Vector3.Zero();
  53883. this._tvec = BABYLON.Vector3.Zero();
  53884. this._qvec = BABYLON.Vector3.Zero();
  53885. }
  53886. vertex1.subtractToRef(vertex0, this._edge1);
  53887. vertex2.subtractToRef(vertex0, this._edge2);
  53888. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  53889. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  53890. if (det === 0) {
  53891. return null;
  53892. }
  53893. var invdet = 1 / det;
  53894. this.origin.subtractToRef(vertex0, this._tvec);
  53895. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  53896. if (bu < 0 || bu > 1.0) {
  53897. return null;
  53898. }
  53899. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  53900. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  53901. if (bv < 0 || bu + bv > 1.0) {
  53902. return null;
  53903. }
  53904. //check if the distance is longer than the predefined length.
  53905. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  53906. if (distance > this.length) {
  53907. return null;
  53908. }
  53909. return new BABYLON.IntersectionInfo(bu, bv, distance);
  53910. };
  53911. Ray.prototype.intersectsPlane = function (plane) {
  53912. var distance;
  53913. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  53914. if (Math.abs(result1) < 9.99999997475243E-07) {
  53915. return null;
  53916. }
  53917. else {
  53918. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  53919. distance = (-plane.d - result2) / result1;
  53920. if (distance < 0.0) {
  53921. if (distance < -9.99999997475243E-07) {
  53922. return null;
  53923. }
  53924. else {
  53925. return 0;
  53926. }
  53927. }
  53928. return distance;
  53929. }
  53930. };
  53931. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  53932. var tm = BABYLON.Tmp.Matrix[0];
  53933. mesh.getWorldMatrix().invertToRef(tm);
  53934. if (this._tmpRay) {
  53935. Ray.TransformToRef(this, tm, this._tmpRay);
  53936. }
  53937. else {
  53938. this._tmpRay = Ray.Transform(this, tm);
  53939. }
  53940. return mesh.intersects(this._tmpRay, fastCheck);
  53941. };
  53942. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  53943. if (results) {
  53944. results.length = 0;
  53945. }
  53946. else {
  53947. results = [];
  53948. }
  53949. for (var i = 0; i < meshes.length; i++) {
  53950. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  53951. if (pickInfo.hit) {
  53952. results.push(pickInfo);
  53953. }
  53954. }
  53955. results.sort(this._comparePickingInfo);
  53956. return results;
  53957. };
  53958. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  53959. if (pickingInfoA.distance < pickingInfoB.distance) {
  53960. return -1;
  53961. }
  53962. else if (pickingInfoA.distance > pickingInfoB.distance) {
  53963. return 1;
  53964. }
  53965. else {
  53966. return 0;
  53967. }
  53968. };
  53969. /**
  53970. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  53971. * @param sega the first point of the segment to test the intersection against
  53972. * @param segb the second point of the segment to test the intersection against
  53973. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  53974. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  53975. */
  53976. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  53977. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  53978. var u = segb.subtract(sega);
  53979. var v = rsegb.subtract(this.origin);
  53980. var w = sega.subtract(this.origin);
  53981. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  53982. var b = BABYLON.Vector3.Dot(u, v);
  53983. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  53984. var d = BABYLON.Vector3.Dot(u, w);
  53985. var e = BABYLON.Vector3.Dot(v, w);
  53986. var D = a * c - b * b; // always >= 0
  53987. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  53988. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  53989. // compute the line parameters of the two closest points
  53990. if (D < Ray.smallnum) { // the lines are almost parallel
  53991. sN = 0.0; // force using point P0 on segment S1
  53992. sD = 1.0; // to prevent possible division by 0.0 later
  53993. tN = e;
  53994. tD = c;
  53995. }
  53996. else { // get the closest points on the infinite lines
  53997. sN = (b * e - c * d);
  53998. tN = (a * e - b * d);
  53999. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54000. sN = 0.0;
  54001. tN = e;
  54002. tD = c;
  54003. }
  54004. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54005. sN = sD;
  54006. tN = e + b;
  54007. tD = c;
  54008. }
  54009. }
  54010. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54011. tN = 0.0;
  54012. // recompute sc for this edge
  54013. if (-d < 0.0) {
  54014. sN = 0.0;
  54015. }
  54016. else if (-d > a)
  54017. sN = sD;
  54018. else {
  54019. sN = -d;
  54020. sD = a;
  54021. }
  54022. }
  54023. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54024. tN = tD;
  54025. // recompute sc for this edge
  54026. if ((-d + b) < 0.0) {
  54027. sN = 0;
  54028. }
  54029. else if ((-d + b) > a) {
  54030. sN = sD;
  54031. }
  54032. else {
  54033. sN = (-d + b);
  54034. sD = a;
  54035. }
  54036. }
  54037. // finally do the division to get sc and tc
  54038. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54039. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54040. // get the difference of the two closest points
  54041. var qtc = v.multiplyByFloats(tc, tc, tc);
  54042. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54043. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54044. if (isIntersected) {
  54045. return qtc.length();
  54046. }
  54047. return -1;
  54048. };
  54049. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54050. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54051. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54052. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54053. this.direction.normalize();
  54054. return this;
  54055. };
  54056. // Statics
  54057. Ray.Zero = function () {
  54058. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54059. };
  54060. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54061. var result = Ray.Zero();
  54062. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54063. };
  54064. /**
  54065. * 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
  54066. * transformed to the given world matrix.
  54067. * @param origin The origin point
  54068. * @param end The end point
  54069. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54070. */
  54071. Ray.CreateNewFromTo = function (origin, end, world) {
  54072. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54073. var direction = end.subtract(origin);
  54074. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54075. direction.normalize();
  54076. return Ray.Transform(new Ray(origin, direction, length), world);
  54077. };
  54078. Ray.Transform = function (ray, matrix) {
  54079. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54080. Ray.TransformToRef(ray, matrix, result);
  54081. return result;
  54082. };
  54083. Ray.TransformToRef = function (ray, matrix, result) {
  54084. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54085. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54086. result.length = ray.length;
  54087. var dir = result.direction;
  54088. var len = dir.length();
  54089. if (!(len === 0 || len === 1)) {
  54090. var num = 1.0 / len;
  54091. dir.x *= num;
  54092. dir.y *= num;
  54093. dir.z *= num;
  54094. result.length *= len;
  54095. }
  54096. };
  54097. Ray.smallnum = 0.00000001;
  54098. Ray.rayl = 10e8;
  54099. return Ray;
  54100. }());
  54101. BABYLON.Ray = Ray;
  54102. })(BABYLON || (BABYLON = {}));
  54103. //# sourceMappingURL=babylon.ray.js.map
  54104. var BABYLON;
  54105. (function (BABYLON) {
  54106. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54107. if (boxMin.x > sphereCenter.x + sphereRadius)
  54108. return false;
  54109. if (sphereCenter.x - sphereRadius > boxMax.x)
  54110. return false;
  54111. if (boxMin.y > sphereCenter.y + sphereRadius)
  54112. return false;
  54113. if (sphereCenter.y - sphereRadius > boxMax.y)
  54114. return false;
  54115. if (boxMin.z > sphereCenter.z + sphereRadius)
  54116. return false;
  54117. if (sphereCenter.z - sphereRadius > boxMax.z)
  54118. return false;
  54119. return true;
  54120. };
  54121. var getLowestRoot = (function () {
  54122. var result = { root: 0, found: false };
  54123. return function (a, b, c, maxR) {
  54124. result.root = 0;
  54125. result.found = false;
  54126. var determinant = b * b - 4.0 * a * c;
  54127. if (determinant < 0)
  54128. return result;
  54129. var sqrtD = Math.sqrt(determinant);
  54130. var r1 = (-b - sqrtD) / (2.0 * a);
  54131. var r2 = (-b + sqrtD) / (2.0 * a);
  54132. if (r1 > r2) {
  54133. var temp = r2;
  54134. r2 = r1;
  54135. r1 = temp;
  54136. }
  54137. if (r1 > 0 && r1 < maxR) {
  54138. result.root = r1;
  54139. result.found = true;
  54140. return result;
  54141. }
  54142. if (r2 > 0 && r2 < maxR) {
  54143. result.root = r2;
  54144. result.found = true;
  54145. return result;
  54146. }
  54147. return result;
  54148. };
  54149. })();
  54150. var Collider = /** @class */ (function () {
  54151. function Collider() {
  54152. this._collisionPoint = BABYLON.Vector3.Zero();
  54153. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54154. this._tempVector = BABYLON.Vector3.Zero();
  54155. this._tempVector2 = BABYLON.Vector3.Zero();
  54156. this._tempVector3 = BABYLON.Vector3.Zero();
  54157. this._tempVector4 = BABYLON.Vector3.Zero();
  54158. this._edge = BABYLON.Vector3.Zero();
  54159. this._baseToVertex = BABYLON.Vector3.Zero();
  54160. this._destinationPoint = BABYLON.Vector3.Zero();
  54161. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54162. this._displacementVector = BABYLON.Vector3.Zero();
  54163. this._radius = BABYLON.Vector3.One();
  54164. this._retry = 0;
  54165. this._basePointWorld = BABYLON.Vector3.Zero();
  54166. this._velocityWorld = BABYLON.Vector3.Zero();
  54167. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54168. this._collisionMask = -1;
  54169. }
  54170. Object.defineProperty(Collider.prototype, "collisionMask", {
  54171. get: function () {
  54172. return this._collisionMask;
  54173. },
  54174. set: function (mask) {
  54175. this._collisionMask = !isNaN(mask) ? mask : -1;
  54176. },
  54177. enumerable: true,
  54178. configurable: true
  54179. });
  54180. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54181. /**
  54182. * Gets the plane normal used to compute the sliding response (in local space)
  54183. */
  54184. get: function () {
  54185. return this._slidePlaneNormal;
  54186. },
  54187. enumerable: true,
  54188. configurable: true
  54189. });
  54190. // Methods
  54191. Collider.prototype._initialize = function (source, dir, e) {
  54192. this._velocity = dir;
  54193. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54194. this._basePoint = source;
  54195. source.multiplyToRef(this._radius, this._basePointWorld);
  54196. dir.multiplyToRef(this._radius, this._velocityWorld);
  54197. this._velocityWorldLength = this._velocityWorld.length();
  54198. this._epsilon = e;
  54199. this.collisionFound = false;
  54200. };
  54201. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54202. pa.subtractToRef(point, this._tempVector);
  54203. pb.subtractToRef(point, this._tempVector2);
  54204. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54205. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54206. if (d < 0)
  54207. return false;
  54208. pc.subtractToRef(point, this._tempVector3);
  54209. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54210. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54211. if (d < 0)
  54212. return false;
  54213. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54214. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54215. return d >= 0;
  54216. };
  54217. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54218. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54219. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54220. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54221. return false;
  54222. }
  54223. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54224. return false;
  54225. return true;
  54226. };
  54227. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54228. var t0;
  54229. var embeddedInPlane = false;
  54230. //defensive programming, actually not needed.
  54231. if (!trianglePlaneArray) {
  54232. trianglePlaneArray = [];
  54233. }
  54234. if (!trianglePlaneArray[faceIndex]) {
  54235. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54236. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54237. }
  54238. var trianglePlane = trianglePlaneArray[faceIndex];
  54239. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54240. return;
  54241. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54242. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54243. if (normalDotVelocity == 0) {
  54244. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54245. return;
  54246. embeddedInPlane = true;
  54247. t0 = 0;
  54248. }
  54249. else {
  54250. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54251. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54252. if (t0 > t1) {
  54253. var temp = t1;
  54254. t1 = t0;
  54255. t0 = temp;
  54256. }
  54257. if (t0 > 1.0 || t1 < 0.0)
  54258. return;
  54259. if (t0 < 0)
  54260. t0 = 0;
  54261. if (t0 > 1.0)
  54262. t0 = 1.0;
  54263. }
  54264. this._collisionPoint.copyFromFloats(0, 0, 0);
  54265. var found = false;
  54266. var t = 1.0;
  54267. if (!embeddedInPlane) {
  54268. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54269. this._velocity.scaleToRef(t0, this._tempVector);
  54270. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54271. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54272. found = true;
  54273. t = t0;
  54274. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54275. }
  54276. }
  54277. if (!found) {
  54278. var velocitySquaredLength = this._velocity.lengthSquared();
  54279. var a = velocitySquaredLength;
  54280. this._basePoint.subtractToRef(p1, this._tempVector);
  54281. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54282. var c = this._tempVector.lengthSquared() - 1.0;
  54283. var lowestRoot = getLowestRoot(a, b, c, t);
  54284. if (lowestRoot.found) {
  54285. t = lowestRoot.root;
  54286. found = true;
  54287. this._collisionPoint.copyFrom(p1);
  54288. }
  54289. this._basePoint.subtractToRef(p2, this._tempVector);
  54290. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54291. c = this._tempVector.lengthSquared() - 1.0;
  54292. lowestRoot = getLowestRoot(a, b, c, t);
  54293. if (lowestRoot.found) {
  54294. t = lowestRoot.root;
  54295. found = true;
  54296. this._collisionPoint.copyFrom(p2);
  54297. }
  54298. this._basePoint.subtractToRef(p3, this._tempVector);
  54299. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54300. c = this._tempVector.lengthSquared() - 1.0;
  54301. lowestRoot = getLowestRoot(a, b, c, t);
  54302. if (lowestRoot.found) {
  54303. t = lowestRoot.root;
  54304. found = true;
  54305. this._collisionPoint.copyFrom(p3);
  54306. }
  54307. p2.subtractToRef(p1, this._edge);
  54308. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54309. var edgeSquaredLength = this._edge.lengthSquared();
  54310. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54311. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54312. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54313. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54314. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54315. lowestRoot = getLowestRoot(a, b, c, t);
  54316. if (lowestRoot.found) {
  54317. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54318. if (f >= 0.0 && f <= 1.0) {
  54319. t = lowestRoot.root;
  54320. found = true;
  54321. this._edge.scaleInPlace(f);
  54322. p1.addToRef(this._edge, this._collisionPoint);
  54323. }
  54324. }
  54325. p3.subtractToRef(p2, this._edge);
  54326. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54327. edgeSquaredLength = this._edge.lengthSquared();
  54328. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54329. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54330. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54331. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54332. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54333. lowestRoot = getLowestRoot(a, b, c, t);
  54334. if (lowestRoot.found) {
  54335. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54336. if (f >= 0.0 && f <= 1.0) {
  54337. t = lowestRoot.root;
  54338. found = true;
  54339. this._edge.scaleInPlace(f);
  54340. p2.addToRef(this._edge, this._collisionPoint);
  54341. }
  54342. }
  54343. p1.subtractToRef(p3, this._edge);
  54344. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54345. edgeSquaredLength = this._edge.lengthSquared();
  54346. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54347. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54348. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54349. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54350. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54351. lowestRoot = getLowestRoot(a, b, c, t);
  54352. if (lowestRoot.found) {
  54353. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54354. if (f >= 0.0 && f <= 1.0) {
  54355. t = lowestRoot.root;
  54356. found = true;
  54357. this._edge.scaleInPlace(f);
  54358. p3.addToRef(this._edge, this._collisionPoint);
  54359. }
  54360. }
  54361. }
  54362. if (found) {
  54363. var distToCollision = t * this._velocity.length();
  54364. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54365. if (!this.intersectionPoint) {
  54366. this.intersectionPoint = this._collisionPoint.clone();
  54367. }
  54368. else {
  54369. this.intersectionPoint.copyFrom(this._collisionPoint);
  54370. }
  54371. this._nearestDistance = distToCollision;
  54372. this.collisionFound = true;
  54373. }
  54374. }
  54375. };
  54376. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54377. for (var i = indexStart; i < indexEnd; i += 3) {
  54378. var p1 = pts[indices[i] - decal];
  54379. var p2 = pts[indices[i + 1] - decal];
  54380. var p3 = pts[indices[i + 2] - decal];
  54381. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54382. }
  54383. };
  54384. Collider.prototype._getResponse = function (pos, vel) {
  54385. pos.addToRef(vel, this._destinationPoint);
  54386. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54387. this._basePoint.addToRef(vel, pos);
  54388. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54389. this._slidePlaneNormal.normalize();
  54390. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54391. pos.addInPlace(this._displacementVector);
  54392. this.intersectionPoint.addInPlace(this._displacementVector);
  54393. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54394. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54395. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54396. };
  54397. return Collider;
  54398. }());
  54399. BABYLON.Collider = Collider;
  54400. })(BABYLON || (BABYLON = {}));
  54401. //# sourceMappingURL=babylon.collider.js.map
  54402. var BABYLON;
  54403. (function (BABYLON) {
  54404. //WebWorker code will be inserted to this variable.
  54405. BABYLON.CollisionWorker = "";
  54406. /** Defines supported task for worker process */
  54407. var WorkerTaskType;
  54408. (function (WorkerTaskType) {
  54409. /** Initialization */
  54410. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54411. /** Update of geometry */
  54412. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54413. /** Evaluate collision */
  54414. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54415. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54416. /** Defines kind of replies returned by worker */
  54417. var WorkerReplyType;
  54418. (function (WorkerReplyType) {
  54419. /** Success */
  54420. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54421. /** Unkown error */
  54422. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54423. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54424. var CollisionCoordinatorWorker = /** @class */ (function () {
  54425. function CollisionCoordinatorWorker() {
  54426. var _this = this;
  54427. this._scaledPosition = BABYLON.Vector3.Zero();
  54428. this._scaledVelocity = BABYLON.Vector3.Zero();
  54429. this.onMeshUpdated = function (transformNode) {
  54430. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54431. };
  54432. this.onGeometryUpdated = function (geometry) {
  54433. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54434. };
  54435. this._afterRender = function () {
  54436. if (!_this._init)
  54437. return;
  54438. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54439. return;
  54440. }
  54441. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54442. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54443. if (_this._runningUpdated > 4) {
  54444. return;
  54445. }
  54446. ++_this._runningUpdated;
  54447. var payload = {
  54448. updatedMeshes: _this._addUpdateMeshesList,
  54449. updatedGeometries: _this._addUpdateGeometriesList,
  54450. removedGeometries: _this._toRemoveGeometryArray,
  54451. removedMeshes: _this._toRemoveMeshesArray
  54452. };
  54453. var message = {
  54454. payload: payload,
  54455. taskType: WorkerTaskType.UPDATE
  54456. };
  54457. var serializable = [];
  54458. for (var id in payload.updatedGeometries) {
  54459. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54460. //prepare transferables
  54461. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54462. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54463. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54464. }
  54465. }
  54466. _this._worker.postMessage(message, serializable);
  54467. _this._addUpdateMeshesList = {};
  54468. _this._addUpdateGeometriesList = {};
  54469. _this._toRemoveGeometryArray = [];
  54470. _this._toRemoveMeshesArray = [];
  54471. };
  54472. this._onMessageFromWorker = function (e) {
  54473. var returnData = e.data;
  54474. if (returnData.error != WorkerReplyType.SUCCESS) {
  54475. //TODO what errors can be returned from the worker?
  54476. BABYLON.Tools.Warn("error returned from worker!");
  54477. return;
  54478. }
  54479. switch (returnData.taskType) {
  54480. case WorkerTaskType.INIT:
  54481. _this._init = true;
  54482. //Update the worked with ALL of the scene's current state
  54483. _this._scene.meshes.forEach(function (mesh) {
  54484. _this.onMeshAdded(mesh);
  54485. });
  54486. _this._scene.getGeometries().forEach(function (geometry) {
  54487. _this.onGeometryAdded(geometry);
  54488. });
  54489. break;
  54490. case WorkerTaskType.UPDATE:
  54491. _this._runningUpdated--;
  54492. break;
  54493. case WorkerTaskType.COLLIDE:
  54494. var returnPayload = returnData.payload;
  54495. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54496. return;
  54497. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54498. if (callback) {
  54499. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54500. if (mesh) {
  54501. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54502. }
  54503. }
  54504. //cleanup
  54505. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54506. break;
  54507. }
  54508. };
  54509. this._collisionsCallbackArray = [];
  54510. this._init = false;
  54511. this._runningUpdated = 0;
  54512. this._addUpdateMeshesList = {};
  54513. this._addUpdateGeometriesList = {};
  54514. this._toRemoveGeometryArray = [];
  54515. this._toRemoveMeshesArray = [];
  54516. }
  54517. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54518. if (!this._init)
  54519. return;
  54520. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54521. return;
  54522. position.divideToRef(collider._radius, this._scaledPosition);
  54523. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54524. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54525. var payload = {
  54526. collider: {
  54527. position: this._scaledPosition.asArray(),
  54528. velocity: this._scaledVelocity.asArray(),
  54529. radius: collider._radius.asArray()
  54530. },
  54531. collisionId: collisionIndex,
  54532. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54533. maximumRetry: maximumRetry
  54534. };
  54535. var message = {
  54536. payload: payload,
  54537. taskType: WorkerTaskType.COLLIDE
  54538. };
  54539. this._worker.postMessage(message);
  54540. };
  54541. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54542. this._scene = scene;
  54543. this._scene.registerAfterRender(this._afterRender);
  54544. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54545. this._worker = new Worker(workerUrl);
  54546. this._worker.onmessage = this._onMessageFromWorker;
  54547. var message = {
  54548. payload: {},
  54549. taskType: WorkerTaskType.INIT
  54550. };
  54551. this._worker.postMessage(message);
  54552. };
  54553. CollisionCoordinatorWorker.prototype.destroy = function () {
  54554. this._scene.unregisterAfterRender(this._afterRender);
  54555. this._worker.terminate();
  54556. };
  54557. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54558. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54559. this.onMeshUpdated(mesh);
  54560. };
  54561. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54562. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54563. };
  54564. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54565. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54566. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54567. this.onGeometryUpdated(geometry);
  54568. };
  54569. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54570. this._toRemoveGeometryArray.push(geometry.id);
  54571. };
  54572. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54573. var submeshes = [];
  54574. if (mesh.subMeshes) {
  54575. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54576. var boundingInfo = sm.getBoundingInfo();
  54577. return {
  54578. position: idx,
  54579. verticesStart: sm.verticesStart,
  54580. verticesCount: sm.verticesCount,
  54581. indexStart: sm.indexStart,
  54582. indexCount: sm.indexCount,
  54583. hasMaterial: !!sm.getMaterial(),
  54584. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54585. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54586. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54587. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54588. };
  54589. });
  54590. }
  54591. var geometryId = null;
  54592. if (mesh instanceof BABYLON.Mesh) {
  54593. var geometry = mesh.geometry;
  54594. geometryId = geometry ? geometry.id : null;
  54595. }
  54596. else if (mesh instanceof BABYLON.InstancedMesh) {
  54597. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54598. geometryId = geometry ? geometry.id : null;
  54599. }
  54600. var boundingInfo = mesh.getBoundingInfo();
  54601. return {
  54602. uniqueId: mesh.uniqueId,
  54603. id: mesh.id,
  54604. name: mesh.name,
  54605. geometryId: geometryId,
  54606. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54607. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54608. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54609. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54610. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54611. subMeshes: submeshes,
  54612. checkCollisions: mesh.checkCollisions
  54613. };
  54614. };
  54615. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54616. return {
  54617. id: geometry.id,
  54618. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54619. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54620. indices: new Uint32Array(geometry.getIndices() || []),
  54621. };
  54622. };
  54623. return CollisionCoordinatorWorker;
  54624. }());
  54625. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54626. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54627. function CollisionCoordinatorLegacy() {
  54628. this._scaledPosition = BABYLON.Vector3.Zero();
  54629. this._scaledVelocity = BABYLON.Vector3.Zero();
  54630. this._finalPosition = BABYLON.Vector3.Zero();
  54631. }
  54632. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54633. position.divideToRef(collider._radius, this._scaledPosition);
  54634. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54635. collider.collidedMesh = null;
  54636. collider._retry = 0;
  54637. collider._initialVelocity = this._scaledVelocity;
  54638. collider._initialPosition = this._scaledPosition;
  54639. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54640. this._finalPosition.multiplyInPlace(collider._radius);
  54641. //run the callback
  54642. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54643. };
  54644. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54645. this._scene = scene;
  54646. };
  54647. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54648. //Legacy need no destruction method.
  54649. };
  54650. //No update in legacy mode
  54651. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54652. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54653. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54654. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54655. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54656. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54657. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54658. if (excludedMesh === void 0) { excludedMesh = null; }
  54659. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54660. if (collider._retry >= maximumRetry) {
  54661. finalPosition.copyFrom(position);
  54662. return;
  54663. }
  54664. // Check if this is a mesh else camera or -1
  54665. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54666. collider._initialize(position, velocity, closeDistance);
  54667. // Check all meshes
  54668. for (var index = 0; index < this._scene.meshes.length; index++) {
  54669. var mesh = this._scene.meshes[index];
  54670. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54671. mesh._checkCollision(collider);
  54672. }
  54673. }
  54674. if (!collider.collisionFound) {
  54675. position.addToRef(velocity, finalPosition);
  54676. return;
  54677. }
  54678. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54679. collider._getResponse(position, velocity);
  54680. }
  54681. if (velocity.length() <= closeDistance) {
  54682. finalPosition.copyFrom(position);
  54683. return;
  54684. }
  54685. collider._retry++;
  54686. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54687. };
  54688. return CollisionCoordinatorLegacy;
  54689. }());
  54690. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54691. })(BABYLON || (BABYLON = {}));
  54692. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54693. var BABYLON;
  54694. (function (BABYLON) {
  54695. /**
  54696. * A particle represents one of the element emitted by a particle system.
  54697. * This is mainly define by its coordinates, direction, velocity and age.
  54698. */
  54699. var Particle = /** @class */ (function () {
  54700. /**
  54701. * Creates a new instance Particle
  54702. * @param particleSystem the particle system the particle belongs to
  54703. */
  54704. function Particle(
  54705. /**
  54706. * particleSystem the particle system the particle belongs to.
  54707. */
  54708. particleSystem) {
  54709. this.particleSystem = particleSystem;
  54710. /**
  54711. * The world position of the particle in the scene.
  54712. */
  54713. this.position = BABYLON.Vector3.Zero();
  54714. /**
  54715. * The world direction of the particle in the scene.
  54716. */
  54717. this.direction = BABYLON.Vector3.Zero();
  54718. /**
  54719. * The color of the particle.
  54720. */
  54721. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54722. /**
  54723. * The color change of the particle per step.
  54724. */
  54725. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54726. /**
  54727. * Defines how long will the life of the particle be.
  54728. */
  54729. this.lifeTime = 1.0;
  54730. /**
  54731. * The current age of the particle.
  54732. */
  54733. this.age = 0;
  54734. /**
  54735. * The current size of the particle.
  54736. */
  54737. this.size = 0;
  54738. /**
  54739. * The current scale of the particle.
  54740. */
  54741. this.scale = new BABYLON.Vector2(1, 1);
  54742. /**
  54743. * The current angle of the particle.
  54744. */
  54745. this.angle = 0;
  54746. /**
  54747. * Defines how fast is the angle changing.
  54748. */
  54749. this.angularSpeed = 0;
  54750. /**
  54751. * Defines the cell index used by the particle to be rendered from a sprite.
  54752. */
  54753. this.cellIndex = 0;
  54754. this._currentFrameCounter = 0;
  54755. if (!this.particleSystem.isAnimationSheetEnabled) {
  54756. return;
  54757. }
  54758. this.updateCellInfoFromSystem();
  54759. }
  54760. Particle.prototype.updateCellInfoFromSystem = function () {
  54761. this.cellIndex = this.particleSystem.startSpriteCellID;
  54762. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  54763. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  54764. }
  54765. else {
  54766. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  54767. }
  54768. };
  54769. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  54770. // (ageOffset / scaledUpdateSpeed) / available cells
  54771. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  54772. this._currentFrameCounter += scaledUpdateSpeed;
  54773. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  54774. this._currentFrameCounter = 0;
  54775. this.cellIndex++;
  54776. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54777. this.cellIndex = this.particleSystem.endSpriteCellID;
  54778. }
  54779. }
  54780. };
  54781. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  54782. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  54783. this.cellIndex++;
  54784. this._currentFrameCounter = 0;
  54785. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54786. if (this.particleSystem.spriteCellLoop) {
  54787. this.cellIndex = this.particleSystem.startSpriteCellID;
  54788. }
  54789. else {
  54790. this.cellIndex = this.particleSystem.endSpriteCellID;
  54791. }
  54792. }
  54793. }
  54794. else {
  54795. this._currentFrameCounter++;
  54796. }
  54797. };
  54798. /**
  54799. * Copy the properties of particle to another one.
  54800. * @param other the particle to copy the information to.
  54801. */
  54802. Particle.prototype.copyTo = function (other) {
  54803. other.position.copyFrom(this.position);
  54804. if (this._initialDirection) {
  54805. if (other._initialDirection) {
  54806. other._initialDirection.copyFrom(this._initialDirection);
  54807. }
  54808. else {
  54809. other._initialDirection = this._initialDirection.clone();
  54810. }
  54811. }
  54812. else {
  54813. other._initialDirection = null;
  54814. }
  54815. other.direction.copyFrom(this.direction);
  54816. other.color.copyFrom(this.color);
  54817. other.colorStep.copyFrom(this.colorStep);
  54818. other.lifeTime = this.lifeTime;
  54819. other.age = this.age;
  54820. other.size = this.size;
  54821. other.scale.copyFrom(this.scale);
  54822. other.angle = this.angle;
  54823. other.angularSpeed = this.angularSpeed;
  54824. other.particleSystem = this.particleSystem;
  54825. other.cellIndex = this.cellIndex;
  54826. };
  54827. return Particle;
  54828. }());
  54829. BABYLON.Particle = Particle;
  54830. })(BABYLON || (BABYLON = {}));
  54831. //# sourceMappingURL=babylon.particle.js.map
  54832. var BABYLON;
  54833. (function (BABYLON) {
  54834. /** @hidden */
  54835. var ColorGradient = /** @class */ (function () {
  54836. function ColorGradient() {
  54837. }
  54838. return ColorGradient;
  54839. }());
  54840. /**
  54841. * This represents a particle system in Babylon.
  54842. * 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.
  54843. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  54844. * @example https://doc.babylonjs.com/babylon101/particles
  54845. */
  54846. var ParticleSystem = /** @class */ (function () {
  54847. /**
  54848. * Instantiates a particle system.
  54849. * 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.
  54850. * @param name The name of the particle system
  54851. * @param capacity The max number of particles alive at the same time
  54852. * @param scene The scene the particle system belongs to
  54853. * @param customEffect a custom effect used to change the way particles are rendered by default
  54854. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  54855. * @param epsilon Offset used to render the particles
  54856. */
  54857. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  54858. if (customEffect === void 0) { customEffect = null; }
  54859. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  54860. if (epsilon === void 0) { epsilon = 0.01; }
  54861. var _this = this;
  54862. /**
  54863. * List of animations used by the particle system.
  54864. */
  54865. this.animations = [];
  54866. /**
  54867. * The rendering group used by the Particle system to chose when to render.
  54868. */
  54869. this.renderingGroupId = 0;
  54870. /**
  54871. * The emitter represents the Mesh or position we are attaching the particle system to.
  54872. */
  54873. this.emitter = null;
  54874. /**
  54875. * The maximum number of particles to emit per frame
  54876. */
  54877. this.emitRate = 10;
  54878. /**
  54879. * If you want to launch only a few particles at once, that can be done, as well.
  54880. */
  54881. this.manualEmitCount = -1;
  54882. /**
  54883. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  54884. */
  54885. this.updateSpeed = 0.01;
  54886. /**
  54887. * The amount of time the particle system is running (depends of the overall update speed).
  54888. */
  54889. this.targetStopDuration = 0;
  54890. /**
  54891. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  54892. */
  54893. this.disposeOnStop = false;
  54894. /**
  54895. * Minimum power of emitting particles.
  54896. */
  54897. this.minEmitPower = 1;
  54898. /**
  54899. * Maximum power of emitting particles.
  54900. */
  54901. this.maxEmitPower = 1;
  54902. /**
  54903. * Minimum life time of emitting particles.
  54904. */
  54905. this.minLifeTime = 1;
  54906. /**
  54907. * Maximum life time of emitting particles.
  54908. */
  54909. this.maxLifeTime = 1;
  54910. /**
  54911. * Minimum Size of emitting particles.
  54912. */
  54913. this.minSize = 1;
  54914. /**
  54915. * Maximum Size of emitting particles.
  54916. */
  54917. this.maxSize = 1;
  54918. /**
  54919. * Minimum scale of emitting particles on X axis.
  54920. */
  54921. this.minScaleX = 1;
  54922. /**
  54923. * Maximum scale of emitting particles on X axis.
  54924. */
  54925. this.maxScaleX = 1;
  54926. /**
  54927. * Minimum scale of emitting particles on Y axis.
  54928. */
  54929. this.minScaleY = 1;
  54930. /**
  54931. * Maximum scale of emitting particles on Y axis.
  54932. */
  54933. this.maxScaleY = 1;
  54934. /**
  54935. * Gets or sets the minimal initial rotation in radians.
  54936. */
  54937. this.minInitialRotation = 0;
  54938. /**
  54939. * Gets or sets the maximal initial rotation in radians.
  54940. */
  54941. this.maxInitialRotation = 0;
  54942. /**
  54943. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  54944. */
  54945. this.minAngularSpeed = 0;
  54946. /**
  54947. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  54948. */
  54949. this.maxAngularSpeed = 0;
  54950. /**
  54951. * The layer mask we are rendering the particles through.
  54952. */
  54953. this.layerMask = 0x0FFFFFFF;
  54954. /**
  54955. * This can help using your own shader to render the particle system.
  54956. * The according effect will be created
  54957. */
  54958. this.customShader = null;
  54959. /**
  54960. * By default particle system starts as soon as they are created. This prevents the
  54961. * automatic start to happen and let you decide when to start emitting particles.
  54962. */
  54963. this.preventAutoStart = false;
  54964. /**
  54965. * Callback triggered when the particle animation is ending.
  54966. */
  54967. this.onAnimationEnd = null;
  54968. /**
  54969. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  54970. */
  54971. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  54972. /**
  54973. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  54974. * to override the particles.
  54975. */
  54976. this.forceDepthWrite = false;
  54977. /**
  54978. * You can use gravity if you want to give an orientation to your particles.
  54979. */
  54980. this.gravity = BABYLON.Vector3.Zero();
  54981. this._colorGradients = null;
  54982. /**
  54983. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  54984. */
  54985. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54986. /**
  54987. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  54988. */
  54989. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54990. /**
  54991. * Color the particle will have at the end of its lifetime
  54992. */
  54993. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  54994. /**
  54995. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  54996. */
  54997. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54998. /**
  54999. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not
  55000. */
  55001. this.spriteCellLoop = true;
  55002. /**
  55003. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop
  55004. */
  55005. this.spriteCellChangeSpeed = 0;
  55006. /**
  55007. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display
  55008. */
  55009. this.startSpriteCellID = 0;
  55010. /**
  55011. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display
  55012. */
  55013. this.endSpriteCellID = 0;
  55014. /**
  55015. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55016. */
  55017. this.spriteCellWidth = 0;
  55018. /**
  55019. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55020. */
  55021. this.spriteCellHeight = 0;
  55022. /** 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 */
  55023. this.preWarmCycles = 0;
  55024. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55025. this.preWarmStepOffset = 1;
  55026. /**
  55027. * An event triggered when the system is disposed
  55028. */
  55029. this.onDisposeObservable = new BABYLON.Observable();
  55030. this._particles = new Array();
  55031. this._stockParticles = new Array();
  55032. this._newPartsExcess = 0;
  55033. this._vertexBuffers = {};
  55034. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55035. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55036. this._scaledDirection = BABYLON.Vector3.Zero();
  55037. this._scaledGravity = BABYLON.Vector3.Zero();
  55038. this._currentRenderId = -1;
  55039. this._useInstancing = false;
  55040. this._started = false;
  55041. this._stopped = false;
  55042. this._actualFrame = 0;
  55043. this._isBillboardBased = true;
  55044. // start of sub system methods
  55045. /**
  55046. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55047. * Its lifetime will start back at 0.
  55048. */
  55049. this.recycleParticle = function (particle) {
  55050. var lastParticle = _this._particles.pop();
  55051. if (lastParticle !== particle) {
  55052. lastParticle.copyTo(particle);
  55053. }
  55054. _this._stockParticles.push(lastParticle);
  55055. };
  55056. this._createParticle = function () {
  55057. var particle;
  55058. if (_this._stockParticles.length !== 0) {
  55059. particle = _this._stockParticles.pop();
  55060. particle.age = 0;
  55061. particle.cellIndex = _this.startSpriteCellID;
  55062. }
  55063. else {
  55064. particle = new BABYLON.Particle(_this);
  55065. }
  55066. return particle;
  55067. };
  55068. this._emitFromParticle = function (particle) {
  55069. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55070. return;
  55071. }
  55072. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55073. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55074. subSystem._rootParticleSystem = _this;
  55075. _this.activeSubSystems.push(subSystem);
  55076. subSystem.start();
  55077. };
  55078. this.id = name;
  55079. this.name = name;
  55080. this._capacity = capacity;
  55081. this._epsilon = epsilon;
  55082. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55083. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55084. this._customEffect = customEffect;
  55085. scene.particleSystems.push(this);
  55086. this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;
  55087. this._createIndexBuffer();
  55088. this._createVertexBuffers();
  55089. // Default emitter type
  55090. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55091. this.updateFunction = function (particles) {
  55092. for (var index = 0; index < particles.length; index++) {
  55093. var particle = particles[index];
  55094. particle.age += _this._scaledUpdateSpeed;
  55095. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55096. _this._emitFromParticle(particle);
  55097. _this.recycleParticle(particle);
  55098. index--;
  55099. continue;
  55100. }
  55101. else {
  55102. if (_this._colorGradients && _this._colorGradients.length > 0) {
  55103. var ratio = particle.age / particle.lifeTime;
  55104. for (var gradientIndex = 0; gradientIndex < _this._colorGradients.length - 1; gradientIndex++) {
  55105. var currentGradient = _this._colorGradients[gradientIndex];
  55106. var nextGradient = _this._colorGradients[gradientIndex + 1];
  55107. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  55108. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  55109. BABYLON.Color4.LerpToRef(currentGradient.color, nextGradient.color, scale, particle.color);
  55110. break;
  55111. }
  55112. }
  55113. }
  55114. else {
  55115. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55116. particle.color.addInPlace(_this._scaledColorStep);
  55117. if (particle.color.a < 0) {
  55118. particle.color.a = 0;
  55119. }
  55120. }
  55121. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55122. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55123. particle.position.addInPlace(_this._scaledDirection);
  55124. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55125. particle.direction.addInPlace(_this._scaledGravity);
  55126. if (_this._isAnimationSheetEnabled) {
  55127. particle.updateCellIndex(_this._scaledUpdateSpeed);
  55128. }
  55129. }
  55130. }
  55131. };
  55132. }
  55133. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55134. /**
  55135. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55136. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55137. */
  55138. get: function () {
  55139. if (this.particleEmitterType.direction1) {
  55140. return this.particleEmitterType.direction1;
  55141. }
  55142. return BABYLON.Vector3.Zero();
  55143. },
  55144. set: function (value) {
  55145. if (this.particleEmitterType.direction1) {
  55146. this.particleEmitterType.direction1 = value;
  55147. }
  55148. },
  55149. enumerable: true,
  55150. configurable: true
  55151. });
  55152. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55153. /**
  55154. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55155. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55156. */
  55157. get: function () {
  55158. if (this.particleEmitterType.direction2) {
  55159. return this.particleEmitterType.direction2;
  55160. }
  55161. return BABYLON.Vector3.Zero();
  55162. },
  55163. set: function (value) {
  55164. if (this.particleEmitterType.direction2) {
  55165. this.particleEmitterType.direction2 = value;
  55166. }
  55167. },
  55168. enumerable: true,
  55169. configurable: true
  55170. });
  55171. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55172. /**
  55173. * 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.
  55174. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55175. */
  55176. get: function () {
  55177. if (this.particleEmitterType.minEmitBox) {
  55178. return this.particleEmitterType.minEmitBox;
  55179. }
  55180. return BABYLON.Vector3.Zero();
  55181. },
  55182. set: function (value) {
  55183. if (this.particleEmitterType.minEmitBox) {
  55184. this.particleEmitterType.minEmitBox = value;
  55185. }
  55186. },
  55187. enumerable: true,
  55188. configurable: true
  55189. });
  55190. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55191. /**
  55192. * 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.
  55193. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55194. */
  55195. get: function () {
  55196. if (this.particleEmitterType.maxEmitBox) {
  55197. return this.particleEmitterType.maxEmitBox;
  55198. }
  55199. return BABYLON.Vector3.Zero();
  55200. },
  55201. set: function (value) {
  55202. if (this.particleEmitterType.maxEmitBox) {
  55203. this.particleEmitterType.maxEmitBox = value;
  55204. }
  55205. },
  55206. enumerable: true,
  55207. configurable: true
  55208. });
  55209. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55210. /**
  55211. * Sets a callback that will be triggered when the system is disposed
  55212. */
  55213. set: function (callback) {
  55214. if (this._onDisposeObserver) {
  55215. this.onDisposeObservable.remove(this._onDisposeObserver);
  55216. }
  55217. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55218. },
  55219. enumerable: true,
  55220. configurable: true
  55221. });
  55222. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55223. /**
  55224. * Gets whether an animation sprite sheet is enabled or not on the particle system
  55225. */
  55226. get: function () {
  55227. return this._isAnimationSheetEnabled;
  55228. },
  55229. enumerable: true,
  55230. configurable: true
  55231. });
  55232. Object.defineProperty(ParticleSystem.prototype, "isBillboardBased", {
  55233. /**
  55234. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55235. */
  55236. get: function () {
  55237. return this._isBillboardBased;
  55238. },
  55239. set: function (value) {
  55240. if (this._isBillboardBased === value) {
  55241. return;
  55242. }
  55243. this._isBillboardBased = value;
  55244. this._resetEffect();
  55245. },
  55246. enumerable: true,
  55247. configurable: true
  55248. });
  55249. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55250. //end of Sub-emitter
  55251. /**
  55252. * Gets the current list of active particles
  55253. */
  55254. get: function () {
  55255. return this._particles;
  55256. },
  55257. enumerable: true,
  55258. configurable: true
  55259. });
  55260. /**
  55261. * Returns the string "ParticleSystem"
  55262. * @returns a string containing the class name
  55263. */
  55264. ParticleSystem.prototype.getClassName = function () {
  55265. return "ParticleSystem";
  55266. };
  55267. /**
  55268. * Adds a new color gradient
  55269. * @param gradient defines the gradient to use (between 0 and 1)
  55270. * @param color defines the color to affect to the specified gradient
  55271. */
  55272. ParticleSystem.prototype.addColorGradient = function (gradient, color) {
  55273. if (!this._colorGradients) {
  55274. this._colorGradients = [];
  55275. }
  55276. var colorGradient = new ColorGradient();
  55277. colorGradient.gradient = gradient;
  55278. colorGradient.color = color;
  55279. this._colorGradients.push(colorGradient);
  55280. this._colorGradients.sort(function (a, b) {
  55281. if (a.gradient < b.gradient) {
  55282. return -1;
  55283. }
  55284. else if (a.gradient > b.gradient) {
  55285. return 1;
  55286. }
  55287. return 0;
  55288. });
  55289. return this;
  55290. };
  55291. /**
  55292. * Remove a specific color gradient
  55293. * @param gradient defines the gradient to remove
  55294. */
  55295. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  55296. if (!this._colorGradients) {
  55297. return this;
  55298. }
  55299. var index = 0;
  55300. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  55301. var colorGradient = _a[_i];
  55302. if (colorGradient.gradient === gradient) {
  55303. this._colorGradients.splice(index, 1);
  55304. break;
  55305. }
  55306. index++;
  55307. }
  55308. return this;
  55309. };
  55310. ParticleSystem.prototype._resetEffect = function () {
  55311. if (this._vertexBuffer) {
  55312. this._vertexBuffer.dispose();
  55313. this._vertexBuffer = null;
  55314. }
  55315. if (this._spriteBuffer) {
  55316. this._spriteBuffer.dispose();
  55317. this._spriteBuffer = null;
  55318. }
  55319. this._createVertexBuffers();
  55320. };
  55321. ParticleSystem.prototype._createVertexBuffers = function () {
  55322. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  55323. if (this._isAnimationSheetEnabled) {
  55324. this._vertexBufferSize += 1;
  55325. }
  55326. if (!this._isBillboardBased) {
  55327. this._vertexBufferSize += 3;
  55328. }
  55329. var engine = this._scene.getEngine();
  55330. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  55331. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  55332. var dataOffset = 0;
  55333. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55334. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55335. dataOffset += 3;
  55336. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  55337. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55338. dataOffset += 4;
  55339. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55340. this._vertexBuffers["angle"] = options;
  55341. dataOffset += 1;
  55342. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55343. this._vertexBuffers["size"] = size;
  55344. dataOffset += 2;
  55345. if (this._isAnimationSheetEnabled) {
  55346. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55347. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55348. dataOffset += 1;
  55349. }
  55350. if (!this._isBillboardBased) {
  55351. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55352. this._vertexBuffers["direction"] = directionBuffer;
  55353. dataOffset += 3;
  55354. }
  55355. var offsets;
  55356. if (this._useInstancing) {
  55357. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  55358. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  55359. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  55360. }
  55361. else {
  55362. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55363. dataOffset += 2;
  55364. }
  55365. this._vertexBuffers["offset"] = offsets;
  55366. };
  55367. ParticleSystem.prototype._createIndexBuffer = function () {
  55368. if (this._useInstancing) {
  55369. return;
  55370. }
  55371. var indices = [];
  55372. var index = 0;
  55373. for (var count = 0; count < this._capacity; count++) {
  55374. indices.push(index);
  55375. indices.push(index + 1);
  55376. indices.push(index + 2);
  55377. indices.push(index);
  55378. indices.push(index + 2);
  55379. indices.push(index + 3);
  55380. index += 4;
  55381. }
  55382. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55383. };
  55384. /**
  55385. * Gets the maximum number of particles active at the same time.
  55386. * @returns The max number of active particles.
  55387. */
  55388. ParticleSystem.prototype.getCapacity = function () {
  55389. return this._capacity;
  55390. };
  55391. /**
  55392. * Gets Wether there are still active particles in the system.
  55393. * @returns True if it is alive, otherwise false.
  55394. */
  55395. ParticleSystem.prototype.isAlive = function () {
  55396. return this._alive;
  55397. };
  55398. /**
  55399. * Gets Wether the system has been started.
  55400. * @returns True if it has been started, otherwise false.
  55401. */
  55402. ParticleSystem.prototype.isStarted = function () {
  55403. return this._started;
  55404. };
  55405. /**
  55406. * Starts the particle system and begins to emit.
  55407. */
  55408. ParticleSystem.prototype.start = function () {
  55409. this._started = true;
  55410. this._stopped = false;
  55411. this._actualFrame = 0;
  55412. if (this.subEmitters && this.subEmitters.length != 0) {
  55413. this.activeSubSystems = new Array();
  55414. }
  55415. if (this.preWarmCycles) {
  55416. for (var index = 0; index < this.preWarmCycles; index++) {
  55417. this.animate(true);
  55418. }
  55419. }
  55420. };
  55421. /**
  55422. * Stops the particle system.
  55423. * @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.
  55424. */
  55425. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55426. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55427. this._stopped = true;
  55428. if (stopSubEmitters) {
  55429. this._stopSubEmitters();
  55430. }
  55431. };
  55432. // animation sheet
  55433. /**
  55434. * Remove all active particles
  55435. */
  55436. ParticleSystem.prototype.reset = function () {
  55437. this._stockParticles = [];
  55438. this._particles = [];
  55439. };
  55440. /**
  55441. * @hidden (for internal use only)
  55442. */
  55443. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55444. var offset = index * this._vertexBufferSize;
  55445. this._vertexData[offset++] = particle.position.x;
  55446. this._vertexData[offset++] = particle.position.y;
  55447. this._vertexData[offset++] = particle.position.z;
  55448. this._vertexData[offset++] = particle.color.r;
  55449. this._vertexData[offset++] = particle.color.g;
  55450. this._vertexData[offset++] = particle.color.b;
  55451. this._vertexData[offset++] = particle.color.a;
  55452. this._vertexData[offset++] = particle.angle;
  55453. this._vertexData[offset++] = particle.scale.x * particle.size;
  55454. this._vertexData[offset++] = particle.scale.y * particle.size;
  55455. if (this._isAnimationSheetEnabled) {
  55456. this._vertexData[offset++] = particle.cellIndex;
  55457. }
  55458. if (!this._isBillboardBased) {
  55459. if (particle._initialDirection) {
  55460. this._vertexData[offset++] = particle._initialDirection.x;
  55461. this._vertexData[offset++] = particle._initialDirection.y;
  55462. this._vertexData[offset++] = particle._initialDirection.z;
  55463. }
  55464. else {
  55465. this._vertexData[offset++] = particle.direction.x;
  55466. this._vertexData[offset++] = particle.direction.y;
  55467. this._vertexData[offset++] = particle.direction.z;
  55468. }
  55469. }
  55470. if (!this._useInstancing) {
  55471. if (this._isAnimationSheetEnabled) {
  55472. if (offsetX === 0)
  55473. offsetX = this._epsilon;
  55474. else if (offsetX === 1)
  55475. offsetX = 1 - this._epsilon;
  55476. if (offsetY === 0)
  55477. offsetY = this._epsilon;
  55478. else if (offsetY === 1)
  55479. offsetY = 1 - this._epsilon;
  55480. }
  55481. this._vertexData[offset++] = offsetX;
  55482. this._vertexData[offset++] = offsetY;
  55483. }
  55484. };
  55485. ParticleSystem.prototype._stopSubEmitters = function () {
  55486. if (!this.activeSubSystems) {
  55487. return;
  55488. }
  55489. this.activeSubSystems.forEach(function (subSystem) {
  55490. subSystem.stop(true);
  55491. });
  55492. this.activeSubSystems = new Array();
  55493. };
  55494. ParticleSystem.prototype._removeFromRoot = function () {
  55495. if (!this._rootParticleSystem) {
  55496. return;
  55497. }
  55498. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55499. if (index !== -1) {
  55500. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55501. }
  55502. };
  55503. // end of sub system methods
  55504. ParticleSystem.prototype._update = function (newParticles) {
  55505. // Update current
  55506. this._alive = this._particles.length > 0;
  55507. this.updateFunction(this._particles);
  55508. // Add new ones
  55509. var worldMatrix;
  55510. if (this.emitter.position) {
  55511. var emitterMesh = this.emitter;
  55512. worldMatrix = emitterMesh.getWorldMatrix();
  55513. }
  55514. else {
  55515. var emitterPosition = this.emitter;
  55516. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55517. }
  55518. var particle;
  55519. for (var index = 0; index < newParticles; index++) {
  55520. if (this._particles.length === this._capacity) {
  55521. break;
  55522. }
  55523. particle = this._createParticle();
  55524. this._particles.push(particle);
  55525. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  55526. if (this.startPositionFunction) {
  55527. this.startPositionFunction(worldMatrix, particle.position, particle);
  55528. }
  55529. else {
  55530. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55531. }
  55532. if (this.startDirectionFunction) {
  55533. this.startDirectionFunction(worldMatrix, particle.direction, particle);
  55534. }
  55535. else {
  55536. this.particleEmitterType.startDirectionFunction(worldMatrix, particle.direction, particle);
  55537. }
  55538. if (emitPower === 0) {
  55539. if (!particle._initialDirection) {
  55540. particle._initialDirection = particle.direction.clone();
  55541. }
  55542. else {
  55543. particle._initialDirection.copyFrom(particle.direction);
  55544. }
  55545. }
  55546. else {
  55547. particle._initialDirection = null;
  55548. }
  55549. particle.direction.scaleInPlace(emitPower);
  55550. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  55551. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  55552. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this.minScaleX, this.maxScaleX), BABYLON.Scalar.RandomRange(this.minScaleY, this.maxScaleY));
  55553. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  55554. particle.angle = BABYLON.Scalar.RandomRange(this.minInitialRotation, this.maxInitialRotation);
  55555. if (!this._colorGradients || this._colorGradients.length === 0) {
  55556. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  55557. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  55558. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  55559. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55560. }
  55561. else {
  55562. particle.color.copyFrom(this._colorGradients[0].color);
  55563. }
  55564. }
  55565. };
  55566. ParticleSystem.prototype._getEffect = function () {
  55567. if (this._customEffect) {
  55568. return this._customEffect;
  55569. }
  55570. ;
  55571. var defines = [];
  55572. if (this._scene.clipPlane) {
  55573. defines.push("#define CLIPPLANE");
  55574. }
  55575. if (this._isAnimationSheetEnabled) {
  55576. defines.push("#define ANIMATESHEET");
  55577. }
  55578. if (this._isBillboardBased) {
  55579. defines.push("#define BILLBOARD");
  55580. }
  55581. // Effect
  55582. var join = defines.join("\n");
  55583. if (this._cachedDefines !== join) {
  55584. this._cachedDefines = join;
  55585. var attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  55586. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  55587. if (this._isAnimationSheetEnabled) {
  55588. attributesNamesOrOptions.push("cellIndex");
  55589. effectCreationOption.push("particlesInfos");
  55590. }
  55591. if (!this._isBillboardBased) {
  55592. attributesNamesOrOptions.push("direction");
  55593. }
  55594. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  55595. }
  55596. return this._effect;
  55597. };
  55598. /**
  55599. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55600. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  55601. */
  55602. ParticleSystem.prototype.animate = function (preWarmOnly) {
  55603. if (preWarmOnly === void 0) { preWarmOnly = false; }
  55604. if (!this._started)
  55605. return;
  55606. if (!preWarmOnly) {
  55607. var effect = this._getEffect();
  55608. // Check
  55609. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  55610. return;
  55611. if (this._currentRenderId === this._scene.getRenderId()) {
  55612. return;
  55613. }
  55614. this._currentRenderId = this._scene.getRenderId();
  55615. }
  55616. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  55617. // determine the number of particles we need to create
  55618. var newParticles;
  55619. if (this.manualEmitCount > -1) {
  55620. newParticles = this.manualEmitCount;
  55621. this._newPartsExcess = 0;
  55622. this.manualEmitCount = 0;
  55623. }
  55624. else {
  55625. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  55626. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  55627. }
  55628. if (this._newPartsExcess > 1.0) {
  55629. newParticles += this._newPartsExcess >> 0;
  55630. this._newPartsExcess -= this._newPartsExcess >> 0;
  55631. }
  55632. this._alive = false;
  55633. if (!this._stopped) {
  55634. this._actualFrame += this._scaledUpdateSpeed;
  55635. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  55636. this.stop();
  55637. }
  55638. else {
  55639. newParticles = 0;
  55640. }
  55641. this._update(newParticles);
  55642. // Stopped?
  55643. if (this._stopped) {
  55644. if (!this._alive) {
  55645. this._started = false;
  55646. if (this.onAnimationEnd) {
  55647. this.onAnimationEnd();
  55648. }
  55649. if (this.disposeOnStop) {
  55650. this._scene._toBeDisposed.push(this);
  55651. }
  55652. }
  55653. }
  55654. if (!preWarmOnly) {
  55655. // Update VBO
  55656. var offset = 0;
  55657. for (var index = 0; index < this._particles.length; index++) {
  55658. var particle = this._particles[index];
  55659. this._appendParticleVertices(offset, particle);
  55660. offset += this._useInstancing ? 1 : 4;
  55661. }
  55662. if (this._vertexBuffer) {
  55663. this._vertexBuffer.update(this._vertexData);
  55664. }
  55665. }
  55666. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  55667. this.stop();
  55668. }
  55669. };
  55670. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  55671. this._appendParticleVertex(offset++, particle, 0, 0);
  55672. if (!this._useInstancing) {
  55673. this._appendParticleVertex(offset++, particle, 1, 0);
  55674. this._appendParticleVertex(offset++, particle, 1, 1);
  55675. this._appendParticleVertex(offset++, particle, 0, 1);
  55676. }
  55677. };
  55678. /**
  55679. * Rebuilds the particle system.
  55680. */
  55681. ParticleSystem.prototype.rebuild = function () {
  55682. this._createIndexBuffer();
  55683. if (this._vertexBuffer) {
  55684. this._vertexBuffer._rebuild();
  55685. }
  55686. };
  55687. /**
  55688. * Is this system ready to be used/rendered
  55689. * @return true if the system is ready
  55690. */
  55691. ParticleSystem.prototype.isReady = function () {
  55692. var effect = this._getEffect();
  55693. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  55694. return false;
  55695. }
  55696. return true;
  55697. };
  55698. /**
  55699. * Renders the particle system in its current state.
  55700. * @returns the current number of particles
  55701. */
  55702. ParticleSystem.prototype.render = function () {
  55703. var effect = this._getEffect();
  55704. // Check
  55705. if (!this.isReady() || !this._particles.length) {
  55706. return 0;
  55707. }
  55708. var engine = this._scene.getEngine();
  55709. // Render
  55710. engine.enableEffect(effect);
  55711. engine.setState(false);
  55712. var viewMatrix = this._scene.getViewMatrix();
  55713. effect.setTexture("diffuseSampler", this.particleTexture);
  55714. effect.setMatrix("view", viewMatrix);
  55715. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55716. if (this._isAnimationSheetEnabled && this.particleTexture) {
  55717. var baseSize = this.particleTexture.getBaseSize();
  55718. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  55719. }
  55720. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  55721. if (this._scene.clipPlane) {
  55722. var clipPlane = this._scene.clipPlane;
  55723. var invView = viewMatrix.clone();
  55724. invView.invert();
  55725. effect.setMatrix("invView", invView);
  55726. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  55727. }
  55728. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55729. // Draw order
  55730. switch (this.blendMode) {
  55731. case ParticleSystem.BLENDMODE_ADD:
  55732. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  55733. break;
  55734. case ParticleSystem.BLENDMODE_ONEONE:
  55735. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  55736. break;
  55737. case ParticleSystem.BLENDMODE_STANDARD:
  55738. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55739. break;
  55740. }
  55741. if (this.forceDepthWrite) {
  55742. engine.setDepthWrite(true);
  55743. }
  55744. if (this._useInstancing) {
  55745. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  55746. engine.unbindInstanceAttributes();
  55747. }
  55748. else {
  55749. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  55750. }
  55751. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55752. return this._particles.length;
  55753. };
  55754. /**
  55755. * Disposes the particle system and free the associated resources
  55756. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  55757. */
  55758. ParticleSystem.prototype.dispose = function (disposeTexture) {
  55759. if (disposeTexture === void 0) { disposeTexture = true; }
  55760. if (this._vertexBuffer) {
  55761. this._vertexBuffer.dispose();
  55762. this._vertexBuffer = null;
  55763. }
  55764. if (this._spriteBuffer) {
  55765. this._spriteBuffer.dispose();
  55766. this._spriteBuffer = null;
  55767. }
  55768. if (this._indexBuffer) {
  55769. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55770. this._indexBuffer = null;
  55771. }
  55772. if (disposeTexture && this.particleTexture) {
  55773. this.particleTexture.dispose();
  55774. this.particleTexture = null;
  55775. }
  55776. this._removeFromRoot();
  55777. // Remove from scene
  55778. var index = this._scene.particleSystems.indexOf(this);
  55779. if (index > -1) {
  55780. this._scene.particleSystems.splice(index, 1);
  55781. }
  55782. // Callback
  55783. this.onDisposeObservable.notifyObservers(this);
  55784. this.onDisposeObservable.clear();
  55785. };
  55786. /**
  55787. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  55788. * @param radius The radius of the sphere to emit from
  55789. * @returns the emitter
  55790. */
  55791. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  55792. if (radius === void 0) { radius = 1; }
  55793. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  55794. this.particleEmitterType = particleEmitter;
  55795. return particleEmitter;
  55796. };
  55797. /**
  55798. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  55799. * @param radius The radius of the sphere to emit from
  55800. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  55801. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  55802. * @returns the emitter
  55803. */
  55804. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  55805. if (radius === void 0) { radius = 1; }
  55806. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  55807. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  55808. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  55809. this.particleEmitterType = particleEmitter;
  55810. return particleEmitter;
  55811. };
  55812. /**
  55813. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  55814. * @param radius The radius of the cone to emit from
  55815. * @param angle The base angle of the cone
  55816. * @returns the emitter
  55817. */
  55818. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  55819. if (radius === void 0) { radius = 1; }
  55820. if (angle === void 0) { angle = Math.PI / 4; }
  55821. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  55822. this.particleEmitterType = particleEmitter;
  55823. return particleEmitter;
  55824. };
  55825. // 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.
  55826. /**
  55827. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  55828. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55829. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55830. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55831. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55832. * @returns the emitter
  55833. */
  55834. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  55835. var particleEmitter = new BABYLON.BoxParticleEmitter();
  55836. this.particleEmitterType = particleEmitter;
  55837. this.direction1 = direction1;
  55838. this.direction2 = direction2;
  55839. this.minEmitBox = minEmitBox;
  55840. this.maxEmitBox = maxEmitBox;
  55841. return particleEmitter;
  55842. };
  55843. // Clone
  55844. /**
  55845. * Clones the particle system.
  55846. * @param name The name of the cloned object
  55847. * @param newEmitter The new emitter to use
  55848. * @returns the cloned particle system
  55849. */
  55850. ParticleSystem.prototype.clone = function (name, newEmitter) {
  55851. var custom = null;
  55852. var program = null;
  55853. if (this.customShader != null) {
  55854. program = this.customShader;
  55855. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  55856. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  55857. }
  55858. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  55859. result.customShader = program;
  55860. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  55861. if (newEmitter === undefined) {
  55862. newEmitter = this.emitter;
  55863. }
  55864. result.emitter = newEmitter;
  55865. if (this.particleTexture) {
  55866. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  55867. }
  55868. if (!this.preventAutoStart) {
  55869. result.start();
  55870. }
  55871. return result;
  55872. };
  55873. /**
  55874. * Serializes the particle system to a JSON object.
  55875. * @returns the JSON object
  55876. */
  55877. ParticleSystem.prototype.serialize = function () {
  55878. var serializationObject = {};
  55879. serializationObject.name = this.name;
  55880. serializationObject.id = this.id;
  55881. // Emitter
  55882. if (this.emitter.position) {
  55883. var emitterMesh = this.emitter;
  55884. serializationObject.emitterId = emitterMesh.id;
  55885. }
  55886. else {
  55887. var emitterPosition = this.emitter;
  55888. serializationObject.emitter = emitterPosition.asArray();
  55889. }
  55890. serializationObject.capacity = this.getCapacity();
  55891. if (this.particleTexture) {
  55892. serializationObject.textureName = this.particleTexture.name;
  55893. }
  55894. // Animations
  55895. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  55896. // Particle system
  55897. serializationObject.minAngularSpeed = this.minAngularSpeed;
  55898. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  55899. serializationObject.minSize = this.minSize;
  55900. serializationObject.maxSize = this.maxSize;
  55901. serializationObject.minScaleX = this.minScaleX;
  55902. serializationObject.maxScaleX = this.maxScaleX;
  55903. serializationObject.minScaleY = this.minScaleY;
  55904. serializationObject.maxScaleY = this.maxScaleY;
  55905. serializationObject.minEmitPower = this.minEmitPower;
  55906. serializationObject.maxEmitPower = this.maxEmitPower;
  55907. serializationObject.minLifeTime = this.minLifeTime;
  55908. serializationObject.maxLifeTime = this.maxLifeTime;
  55909. serializationObject.emitRate = this.emitRate;
  55910. serializationObject.minEmitBox = this.minEmitBox.asArray();
  55911. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  55912. serializationObject.gravity = this.gravity.asArray();
  55913. serializationObject.direction1 = this.direction1.asArray();
  55914. serializationObject.direction2 = this.direction2.asArray();
  55915. serializationObject.color1 = this.color1.asArray();
  55916. serializationObject.color2 = this.color2.asArray();
  55917. serializationObject.colorDead = this.colorDead.asArray();
  55918. serializationObject.updateSpeed = this.updateSpeed;
  55919. serializationObject.targetStopDuration = this.targetStopDuration;
  55920. serializationObject.textureMask = this.textureMask.asArray();
  55921. serializationObject.blendMode = this.blendMode;
  55922. serializationObject.customShader = this.customShader;
  55923. serializationObject.preventAutoStart = this.preventAutoStart;
  55924. serializationObject.preWarmCycles = this.preWarmCycles;
  55925. serializationObject.preWarmStepOffset = this.preWarmStepOffset;
  55926. serializationObject.minInitialRotation = this.minInitialRotation;
  55927. serializationObject.maxInitialRotation = this.maxInitialRotation;
  55928. serializationObject.startSpriteCellID = this.startSpriteCellID;
  55929. serializationObject.endSpriteCellID = this.endSpriteCellID;
  55930. serializationObject.spriteCellLoop = this.spriteCellLoop;
  55931. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  55932. serializationObject.spriteCellWidth = this.spriteCellWidth;
  55933. serializationObject.spriteCellHeight = this.spriteCellHeight;
  55934. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  55935. // Emitter
  55936. if (this.particleEmitterType) {
  55937. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  55938. }
  55939. return serializationObject;
  55940. };
  55941. /**
  55942. * Parses a JSON object to create a particle system.
  55943. * @param parsedParticleSystem The JSON object to parse
  55944. * @param scene The scene to create the particle system in
  55945. * @param rootUrl The root url to use to load external dependencies like texture
  55946. * @returns the Parsed particle system
  55947. */
  55948. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  55949. var name = parsedParticleSystem.name;
  55950. var custom = null;
  55951. var program = null;
  55952. if (parsedParticleSystem.customShader) {
  55953. program = parsedParticleSystem.customShader;
  55954. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  55955. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  55956. }
  55957. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  55958. particleSystem.customShader = program;
  55959. if (parsedParticleSystem.id) {
  55960. particleSystem.id = parsedParticleSystem.id;
  55961. }
  55962. // Auto start
  55963. if (parsedParticleSystem.preventAutoStart) {
  55964. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  55965. }
  55966. // Texture
  55967. if (parsedParticleSystem.textureName) {
  55968. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  55969. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  55970. }
  55971. // Emitter
  55972. if (parsedParticleSystem.emitterId) {
  55973. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  55974. }
  55975. else {
  55976. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  55977. }
  55978. // Animations
  55979. if (parsedParticleSystem.animations) {
  55980. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  55981. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  55982. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  55983. }
  55984. }
  55985. if (parsedParticleSystem.autoAnimate) {
  55986. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  55987. }
  55988. // Particle system
  55989. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  55990. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  55991. particleSystem.minSize = parsedParticleSystem.minSize;
  55992. particleSystem.maxSize = parsedParticleSystem.maxSize;
  55993. if (parsedParticleSystem.minScaleX) {
  55994. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  55995. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  55996. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  55997. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  55998. }
  55999. if (parsedParticleSystem.preWarmCycles !== undefined) {
  56000. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  56001. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  56002. }
  56003. if (parsedParticleSystem.minInitialRotation !== undefined) {
  56004. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  56005. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  56006. }
  56007. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56008. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56009. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56010. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56011. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56012. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56013. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56014. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56015. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56016. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56017. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56018. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56019. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56020. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56021. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56022. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56023. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56024. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56025. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56026. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  56027. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56028. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56029. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56030. if (!particleSystem.preventAutoStart) {
  56031. particleSystem.start();
  56032. }
  56033. return particleSystem;
  56034. };
  56035. /**
  56036. * Source color is added to the destination color without alpha affecting the result.
  56037. */
  56038. ParticleSystem.BLENDMODE_ONEONE = 0;
  56039. /**
  56040. * Blend current color and particle color using particle’s alpha.
  56041. */
  56042. ParticleSystem.BLENDMODE_STANDARD = 1;
  56043. /**
  56044. * Add current color and particle color multiplied by particle’s alpha.
  56045. */
  56046. ParticleSystem.BLENDMODE_ADD = 2;
  56047. return ParticleSystem;
  56048. }());
  56049. BABYLON.ParticleSystem = ParticleSystem;
  56050. })(BABYLON || (BABYLON = {}));
  56051. //# sourceMappingURL=babylon.particleSystem.js.map
  56052. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56053. var BABYLON;
  56054. (function (BABYLON) {
  56055. /**
  56056. * Particle emitter emitting particles from the inside of a box.
  56057. * It emits the particles randomly between 2 given directions.
  56058. */
  56059. var BoxParticleEmitter = /** @class */ (function () {
  56060. /**
  56061. * Creates a new instance BoxParticleEmitter
  56062. */
  56063. function BoxParticleEmitter() {
  56064. /**
  56065. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56066. */
  56067. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56068. /**
  56069. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56070. */
  56071. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56072. /**
  56073. * 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.
  56074. */
  56075. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56076. /**
  56077. * 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.
  56078. */
  56079. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56080. }
  56081. /**
  56082. * Called by the particle System when the direction is computed for the created particle.
  56083. * @param worldMatrix is the world matrix of the particle system
  56084. * @param directionToUpdate is the direction vector to update with the result
  56085. * @param particle is the particle we are computed the direction for
  56086. */
  56087. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56088. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56089. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56090. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56091. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56092. };
  56093. /**
  56094. * Called by the particle System when the position is computed for the created particle.
  56095. * @param worldMatrix is the world matrix of the particle system
  56096. * @param positionToUpdate is the position vector to update with the result
  56097. * @param particle is the particle we are computed the position for
  56098. */
  56099. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56100. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56101. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56102. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56103. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56104. };
  56105. /**
  56106. * Clones the current emitter and returns a copy of it
  56107. * @returns the new emitter
  56108. */
  56109. BoxParticleEmitter.prototype.clone = function () {
  56110. var newOne = new BoxParticleEmitter();
  56111. BABYLON.Tools.DeepCopy(this, newOne);
  56112. return newOne;
  56113. };
  56114. /**
  56115. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56116. * @param effect defines the update shader
  56117. */
  56118. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56119. effect.setVector3("direction1", this.direction1);
  56120. effect.setVector3("direction2", this.direction2);
  56121. effect.setVector3("minEmitBox", this.minEmitBox);
  56122. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56123. };
  56124. /**
  56125. * Returns a string to use to update the GPU particles update shader
  56126. * @returns a string containng the defines string
  56127. */
  56128. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56129. return "#define BOXEMITTER";
  56130. };
  56131. /**
  56132. * Returns the string "BoxEmitter"
  56133. * @returns a string containing the class name
  56134. */
  56135. BoxParticleEmitter.prototype.getClassName = function () {
  56136. return "BoxEmitter";
  56137. };
  56138. /**
  56139. * Serializes the particle system to a JSON object.
  56140. * @returns the JSON object
  56141. */
  56142. BoxParticleEmitter.prototype.serialize = function () {
  56143. var serializationObject = {};
  56144. serializationObject.type = this.getClassName();
  56145. serializationObject.direction1 = this.direction1.asArray();
  56146. serializationObject.direction2 = this.direction2.asArray();
  56147. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56148. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56149. return serializationObject;
  56150. };
  56151. /**
  56152. * Parse properties from a JSON object
  56153. * @param serializationObject defines the JSON object
  56154. */
  56155. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56156. this.direction1.copyFrom(serializationObject.direction1);
  56157. this.direction2.copyFrom(serializationObject.direction2);
  56158. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  56159. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  56160. };
  56161. return BoxParticleEmitter;
  56162. }());
  56163. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56164. })(BABYLON || (BABYLON = {}));
  56165. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56166. var BABYLON;
  56167. (function (BABYLON) {
  56168. /**
  56169. * Particle emitter emitting particles from the inside of a cone.
  56170. * It emits the particles alongside the cone volume from the base to the particle.
  56171. * The emission direction might be randomized.
  56172. */
  56173. var ConeParticleEmitter = /** @class */ (function () {
  56174. /**
  56175. * Creates a new instance ConeParticleEmitter
  56176. * @param radius the radius of the emission cone (1 by default)
  56177. * @param angles the cone base angle (PI by default)
  56178. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  56179. */
  56180. function ConeParticleEmitter(radius, angle,
  56181. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  56182. directionRandomizer) {
  56183. if (radius === void 0) { radius = 1; }
  56184. if (angle === void 0) { angle = Math.PI; }
  56185. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56186. this.directionRandomizer = directionRandomizer;
  56187. this.angle = angle;
  56188. this.radius = radius;
  56189. }
  56190. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56191. /**
  56192. * Gets or sets the radius of the emission cone
  56193. */
  56194. get: function () {
  56195. return this._radius;
  56196. },
  56197. set: function (value) {
  56198. this._radius = value;
  56199. this._buildHeight();
  56200. },
  56201. enumerable: true,
  56202. configurable: true
  56203. });
  56204. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  56205. /**
  56206. * Gets or sets the angle of the emission cone
  56207. */
  56208. get: function () {
  56209. return this._angle;
  56210. },
  56211. set: function (value) {
  56212. this._angle = value;
  56213. this._buildHeight();
  56214. },
  56215. enumerable: true,
  56216. configurable: true
  56217. });
  56218. ConeParticleEmitter.prototype._buildHeight = function () {
  56219. if (this._angle !== 0) {
  56220. this._height = this._radius / Math.tan(this._angle / 2);
  56221. }
  56222. else {
  56223. this._height = 1;
  56224. }
  56225. };
  56226. /**
  56227. * Called by the particle System when the direction is computed for the created particle.
  56228. * @param worldMatrix is the world matrix of the particle system
  56229. * @param directionToUpdate is the direction vector to update with the result
  56230. * @param particle is the particle we are computed the direction for
  56231. */
  56232. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56233. if (this._angle === 0) {
  56234. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  56235. }
  56236. else {
  56237. // measure the direction Vector from the emitter to the particle.
  56238. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56239. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56240. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56241. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56242. direction.x += randX;
  56243. direction.y += randY;
  56244. direction.z += randZ;
  56245. direction.normalize();
  56246. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56247. }
  56248. };
  56249. /**
  56250. * Called by the particle System when the position is computed for the created particle.
  56251. * @param worldMatrix is the world matrix of the particle system
  56252. * @param positionToUpdate is the position vector to update with the result
  56253. * @param particle is the particle we are computed the position for
  56254. */
  56255. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56256. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56257. var h = BABYLON.Scalar.RandomRange(0, 1);
  56258. // Better distribution in a cone at normal angles.
  56259. h = 1 - h * h;
  56260. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56261. radius = radius * h;
  56262. var randX = radius * Math.sin(s);
  56263. var randZ = radius * Math.cos(s);
  56264. var randY = h * this._height;
  56265. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56266. };
  56267. /**
  56268. * Clones the current emitter and returns a copy of it
  56269. * @returns the new emitter
  56270. */
  56271. ConeParticleEmitter.prototype.clone = function () {
  56272. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  56273. BABYLON.Tools.DeepCopy(this, newOne);
  56274. return newOne;
  56275. };
  56276. /**
  56277. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56278. * @param effect defines the update shader
  56279. */
  56280. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56281. effect.setFloat("radius", this._radius);
  56282. effect.setFloat("coneAngle", this._angle);
  56283. effect.setFloat("height", this._height);
  56284. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56285. };
  56286. /**
  56287. * Returns a string to use to update the GPU particles update shader
  56288. * @returns a string containng the defines string
  56289. */
  56290. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56291. return "#define CONEEMITTER";
  56292. };
  56293. /**
  56294. * Returns the string "BoxEmitter"
  56295. * @returns a string containing the class name
  56296. */
  56297. ConeParticleEmitter.prototype.getClassName = function () {
  56298. return "ConeEmitter";
  56299. };
  56300. /**
  56301. * Serializes the particle system to a JSON object.
  56302. * @returns the JSON object
  56303. */
  56304. ConeParticleEmitter.prototype.serialize = function () {
  56305. var serializationObject = {};
  56306. serializationObject.type = this.getClassName();
  56307. serializationObject.radius = this._radius;
  56308. serializationObject.angle = this._angle;
  56309. serializationObject.directionRandomizer = this.directionRandomizer;
  56310. return serializationObject;
  56311. };
  56312. /**
  56313. * Parse properties from a JSON object
  56314. * @param serializationObject defines the JSON object
  56315. */
  56316. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56317. this.radius = serializationObject.radius;
  56318. this.angle = serializationObject.angle;
  56319. this.directionRandomizer = serializationObject.directionRandomizer;
  56320. };
  56321. return ConeParticleEmitter;
  56322. }());
  56323. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56324. })(BABYLON || (BABYLON = {}));
  56325. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56326. var BABYLON;
  56327. (function (BABYLON) {
  56328. /**
  56329. * Particle emitter emitting particles from the inside of a sphere.
  56330. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56331. */
  56332. var SphereParticleEmitter = /** @class */ (function () {
  56333. /**
  56334. * Creates a new instance SphereParticleEmitter
  56335. * @param radius the radius of the emission sphere (1 by default)
  56336. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56337. */
  56338. function SphereParticleEmitter(
  56339. /**
  56340. * The radius of the emission sphere.
  56341. */
  56342. radius,
  56343. /**
  56344. * How much to randomize the particle direction [0-1].
  56345. */
  56346. directionRandomizer) {
  56347. if (radius === void 0) { radius = 1; }
  56348. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56349. this.radius = radius;
  56350. this.directionRandomizer = directionRandomizer;
  56351. /**
  56352. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56353. */
  56354. this.radiusRange = 1;
  56355. }
  56356. /**
  56357. * Called by the particle System when the direction is computed for the created particle.
  56358. * @param worldMatrix is the world matrix of the particle system
  56359. * @param directionToUpdate is the direction vector to update with the result
  56360. * @param particle is the particle we are computed the direction for
  56361. */
  56362. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56363. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56364. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56365. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56366. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56367. direction.x += randX;
  56368. direction.y += randY;
  56369. direction.z += randZ;
  56370. direction.normalize();
  56371. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56372. };
  56373. /**
  56374. * Called by the particle System when the position is computed for the created particle.
  56375. * @param worldMatrix is the world matrix of the particle system
  56376. * @param positionToUpdate is the position vector to update with the result
  56377. * @param particle is the particle we are computed the position for
  56378. */
  56379. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56380. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  56381. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  56382. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56383. var theta = Math.acos(2 * v - 1);
  56384. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56385. var randY = randRadius * Math.cos(theta);
  56386. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56387. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56388. };
  56389. /**
  56390. * Clones the current emitter and returns a copy of it
  56391. * @returns the new emitter
  56392. */
  56393. SphereParticleEmitter.prototype.clone = function () {
  56394. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56395. BABYLON.Tools.DeepCopy(this, newOne);
  56396. return newOne;
  56397. };
  56398. /**
  56399. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56400. * @param effect defines the update shader
  56401. */
  56402. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56403. effect.setFloat("radius", this.radius);
  56404. effect.setFloat("radiusRange", this.radiusRange);
  56405. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56406. };
  56407. /**
  56408. * Returns a string to use to update the GPU particles update shader
  56409. * @returns a string containng the defines string
  56410. */
  56411. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56412. return "#define SPHEREEMITTER";
  56413. };
  56414. /**
  56415. * Returns the string "SphereParticleEmitter"
  56416. * @returns a string containing the class name
  56417. */
  56418. SphereParticleEmitter.prototype.getClassName = function () {
  56419. return "SphereParticleEmitter";
  56420. };
  56421. /**
  56422. * Serializes the particle system to a JSON object.
  56423. * @returns the JSON object
  56424. */
  56425. SphereParticleEmitter.prototype.serialize = function () {
  56426. var serializationObject = {};
  56427. serializationObject.type = this.getClassName();
  56428. serializationObject.radius = this.radius;
  56429. serializationObject.directionRandomizer = this.directionRandomizer;
  56430. return serializationObject;
  56431. };
  56432. /**
  56433. * Parse properties from a JSON object
  56434. * @param serializationObject defines the JSON object
  56435. */
  56436. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56437. this.radius = serializationObject.radius;
  56438. this.directionRandomizer = serializationObject.directionRandomizer;
  56439. };
  56440. return SphereParticleEmitter;
  56441. }());
  56442. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56443. /**
  56444. * Particle emitter emitting particles from the inside of a sphere.
  56445. * It emits the particles randomly between two vectors.
  56446. */
  56447. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56448. __extends(SphereDirectedParticleEmitter, _super);
  56449. /**
  56450. * Creates a new instance SphereDirectedParticleEmitter
  56451. * @param radius the radius of the emission sphere (1 by default)
  56452. * @param direction1 the min limit of the emission direction (up vector by default)
  56453. * @param direction2 the max limit of the emission direction (up vector by default)
  56454. */
  56455. function SphereDirectedParticleEmitter(radius,
  56456. /**
  56457. * The min limit of the emission direction.
  56458. */
  56459. direction1,
  56460. /**
  56461. * The max limit of the emission direction.
  56462. */
  56463. direction2) {
  56464. if (radius === void 0) { radius = 1; }
  56465. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56466. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56467. var _this = _super.call(this, radius) || this;
  56468. _this.direction1 = direction1;
  56469. _this.direction2 = direction2;
  56470. return _this;
  56471. }
  56472. /**
  56473. * Called by the particle System when the direction is computed for the created particle.
  56474. * @param worldMatrix is the world matrix of the particle system
  56475. * @param directionToUpdate is the direction vector to update with the result
  56476. * @param particle is the particle we are computed the direction for
  56477. */
  56478. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56479. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56480. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56481. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56482. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56483. };
  56484. /**
  56485. * Clones the current emitter and returns a copy of it
  56486. * @returns the new emitter
  56487. */
  56488. SphereDirectedParticleEmitter.prototype.clone = function () {
  56489. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56490. BABYLON.Tools.DeepCopy(this, newOne);
  56491. return newOne;
  56492. };
  56493. /**
  56494. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56495. * @param effect defines the update shader
  56496. */
  56497. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56498. effect.setFloat("radius", this.radius);
  56499. effect.setFloat("radiusRange", this.radiusRange);
  56500. effect.setVector3("direction1", this.direction1);
  56501. effect.setVector3("direction2", this.direction2);
  56502. };
  56503. /**
  56504. * Returns a string to use to update the GPU particles update shader
  56505. * @returns a string containng the defines string
  56506. */
  56507. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56508. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56509. };
  56510. /**
  56511. * Returns the string "SphereDirectedParticleEmitter"
  56512. * @returns a string containing the class name
  56513. */
  56514. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  56515. return "SphereDirectedParticleEmitter";
  56516. };
  56517. /**
  56518. * Serializes the particle system to a JSON object.
  56519. * @returns the JSON object
  56520. */
  56521. SphereDirectedParticleEmitter.prototype.serialize = function () {
  56522. var serializationObject = _super.prototype.serialize.call(this);
  56523. serializationObject.direction1 = this.direction1.asArray();
  56524. serializationObject.direction2 = this.direction2.asArray();
  56525. return serializationObject;
  56526. };
  56527. /**
  56528. * Parse properties from a JSON object
  56529. * @param serializationObject defines the JSON object
  56530. */
  56531. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  56532. _super.prototype.parse.call(this, serializationObject);
  56533. this.direction1.copyFrom(serializationObject.direction1);
  56534. this.direction2.copyFrom(serializationObject.direction2);
  56535. };
  56536. return SphereDirectedParticleEmitter;
  56537. }(SphereParticleEmitter));
  56538. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  56539. })(BABYLON || (BABYLON = {}));
  56540. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  56541. var __assign = (this && this.__assign) || Object.assign || function(t) {
  56542. for (var s, i = 1, n = arguments.length; i < n; i++) {
  56543. s = arguments[i];
  56544. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  56545. t[p] = s[p];
  56546. }
  56547. return t;
  56548. };
  56549. var BABYLON;
  56550. (function (BABYLON) {
  56551. /**
  56552. * This represents a GPU particle system in Babylon
  56553. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  56554. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  56555. */
  56556. var GPUParticleSystem = /** @class */ (function () {
  56557. /**
  56558. * Instantiates a GPU particle system.
  56559. * 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.
  56560. * @param name The name of the particle system
  56561. * @param capacity The max number of particles alive at the same time
  56562. * @param scene The scene the particle system belongs to
  56563. */
  56564. function GPUParticleSystem(name, options, scene) {
  56565. /**
  56566. * The emitter represents the Mesh or position we are attaching the particle system to.
  56567. */
  56568. this.emitter = null;
  56569. /**
  56570. * The rendering group used by the Particle system to chose when to render.
  56571. */
  56572. this.renderingGroupId = 0;
  56573. /**
  56574. * The layer mask we are rendering the particles through.
  56575. */
  56576. this.layerMask = 0x0FFFFFFF;
  56577. this._targetIndex = 0;
  56578. this._currentRenderId = -1;
  56579. this._started = false;
  56580. this._stopped = false;
  56581. this._timeDelta = 0;
  56582. this._attributesStrideSize = 18;
  56583. this._actualFrame = 0;
  56584. /**
  56585. * List of animations used by the particle system.
  56586. */
  56587. this.animations = [];
  56588. /**
  56589. * An event triggered when the system is disposed.
  56590. */
  56591. this.onDisposeObservable = new BABYLON.Observable();
  56592. /**
  56593. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56594. */
  56595. this.updateSpeed = 0.01;
  56596. /**
  56597. * The amount of time the particle system is running (depends of the overall update speed).
  56598. */
  56599. this.targetStopDuration = 0;
  56600. /**
  56601. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56602. */
  56603. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  56604. /**
  56605. * Minimum life time of emitting particles.
  56606. */
  56607. this.minLifeTime = 1;
  56608. /**
  56609. * Maximum life time of emitting particles.
  56610. */
  56611. this.maxLifeTime = 1;
  56612. /**
  56613. * Minimum Size of emitting particles.
  56614. */
  56615. this.minSize = 1;
  56616. /**
  56617. * Maximum Size of emitting particles.
  56618. */
  56619. this.maxSize = 1;
  56620. /**
  56621. * Minimum scale of emitting particles on X axis.
  56622. */
  56623. this.minScaleX = 1;
  56624. /**
  56625. * Maximum scale of emitting particles on X axis.
  56626. */
  56627. this.maxScaleX = 1;
  56628. /**
  56629. * Minimum scale of emitting particles on Y axis.
  56630. */
  56631. this.minScaleY = 1;
  56632. /**
  56633. * Maximum scale of emitting particles on Y axis.
  56634. */
  56635. this.maxScaleY = 1;
  56636. /**
  56637. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56638. */
  56639. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56640. /**
  56641. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56642. */
  56643. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56644. /**
  56645. * Color the particle will have at the end of its lifetime.
  56646. */
  56647. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  56648. /**
  56649. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  56650. */
  56651. this.emitRate = 100;
  56652. /**
  56653. * You can use gravity if you want to give an orientation to your particles.
  56654. */
  56655. this.gravity = BABYLON.Vector3.Zero();
  56656. /**
  56657. * Minimum power of emitting particles.
  56658. */
  56659. this.minEmitPower = 1;
  56660. /**
  56661. * Maximum power of emitting particles.
  56662. */
  56663. this.maxEmitPower = 1;
  56664. /**
  56665. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56666. */
  56667. this.minAngularSpeed = 0;
  56668. /**
  56669. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56670. */
  56671. this.maxAngularSpeed = 0;
  56672. /**
  56673. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56674. * to override the particles.
  56675. */
  56676. this.forceDepthWrite = false;
  56677. this._isBillboardBased = true;
  56678. this.id = name;
  56679. this.name = name;
  56680. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56681. this._engine = this._scene.getEngine();
  56682. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  56683. this._capacity = fullOptions.capacity;
  56684. this._activeCount = fullOptions.capacity;
  56685. this._currentActiveCount = 0;
  56686. this._scene.particleSystems.push(this);
  56687. this._updateEffectOptions = {
  56688. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle"],
  56689. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  56690. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  56691. "angleRange", "radiusRange"],
  56692. uniformBuffersNames: [],
  56693. samplers: ["randomSampler"],
  56694. defines: "",
  56695. fallbacks: null,
  56696. onCompiled: null,
  56697. onError: null,
  56698. indexParameters: null,
  56699. maxSimultaneousLights: 0,
  56700. transformFeedbackVaryings: []
  56701. };
  56702. // Random data
  56703. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  56704. var d = [];
  56705. for (var i = 0; i < maxTextureSize; ++i) {
  56706. d.push(Math.random());
  56707. d.push(Math.random());
  56708. d.push(Math.random());
  56709. d.push(Math.random());
  56710. }
  56711. 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);
  56712. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56713. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56714. this._randomTextureSize = maxTextureSize;
  56715. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56716. }
  56717. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  56718. /**
  56719. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  56720. */
  56721. get: function () {
  56722. if (!BABYLON.Engine.LastCreatedEngine) {
  56723. return false;
  56724. }
  56725. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  56726. },
  56727. enumerable: true,
  56728. configurable: true
  56729. });
  56730. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  56731. /**
  56732. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56733. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56734. */
  56735. get: function () {
  56736. if (this.particleEmitterType.direction1) {
  56737. return this.particleEmitterType.direction1;
  56738. }
  56739. return BABYLON.Vector3.Zero();
  56740. },
  56741. set: function (value) {
  56742. if (this.particleEmitterType.direction1) {
  56743. this.particleEmitterType.direction1 = value;
  56744. }
  56745. },
  56746. enumerable: true,
  56747. configurable: true
  56748. });
  56749. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  56750. /**
  56751. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56752. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56753. */
  56754. get: function () {
  56755. if (this.particleEmitterType.direction2) {
  56756. return this.particleEmitterType.direction2;
  56757. }
  56758. return BABYLON.Vector3.Zero();
  56759. },
  56760. set: function (value) {
  56761. if (this.particleEmitterType.direction2) {
  56762. this.particleEmitterType.direction2 = value;
  56763. }
  56764. },
  56765. enumerable: true,
  56766. configurable: true
  56767. });
  56768. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  56769. /**
  56770. * 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.
  56771. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56772. */
  56773. get: function () {
  56774. if (this.particleEmitterType.minEmitBox) {
  56775. return this.particleEmitterType.minEmitBox;
  56776. }
  56777. return BABYLON.Vector3.Zero();
  56778. },
  56779. set: function (value) {
  56780. if (this.particleEmitterType.minEmitBox) {
  56781. this.particleEmitterType.minEmitBox = value;
  56782. }
  56783. },
  56784. enumerable: true,
  56785. configurable: true
  56786. });
  56787. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  56788. /**
  56789. * 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.
  56790. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56791. */
  56792. get: function () {
  56793. if (this.particleEmitterType.maxEmitBox) {
  56794. return this.particleEmitterType.maxEmitBox;
  56795. }
  56796. return BABYLON.Vector3.Zero();
  56797. },
  56798. set: function (value) {
  56799. if (this.particleEmitterType.maxEmitBox) {
  56800. this.particleEmitterType.maxEmitBox = value;
  56801. }
  56802. },
  56803. enumerable: true,
  56804. configurable: true
  56805. });
  56806. /**
  56807. * Gets the maximum number of particles active at the same time.
  56808. * @returns The max number of active particles.
  56809. */
  56810. GPUParticleSystem.prototype.getCapacity = function () {
  56811. return this._capacity;
  56812. };
  56813. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  56814. /**
  56815. * Gets or set the number of active particles
  56816. */
  56817. get: function () {
  56818. return this._activeCount;
  56819. },
  56820. set: function (value) {
  56821. this._activeCount = Math.min(value, this._capacity);
  56822. },
  56823. enumerable: true,
  56824. configurable: true
  56825. });
  56826. /**
  56827. * Is this system ready to be used/rendered
  56828. * @return true if the system is ready
  56829. */
  56830. GPUParticleSystem.prototype.isReady = function () {
  56831. if (!this._updateEffect) {
  56832. this._recreateUpdateEffect();
  56833. this._recreateRenderEffect();
  56834. return false;
  56835. }
  56836. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56837. return false;
  56838. }
  56839. return true;
  56840. };
  56841. /**
  56842. * Gets Wether the system has been started.
  56843. * @returns True if it has been started, otherwise false.
  56844. */
  56845. GPUParticleSystem.prototype.isStarted = function () {
  56846. return this._started;
  56847. };
  56848. /**
  56849. * Starts the particle system and begins to emit.
  56850. */
  56851. GPUParticleSystem.prototype.start = function () {
  56852. this._started = true;
  56853. this._stopped = false;
  56854. };
  56855. /**
  56856. * Stops the particle system.
  56857. */
  56858. GPUParticleSystem.prototype.stop = function () {
  56859. this._stopped = true;
  56860. };
  56861. /**
  56862. * Remove all active particles
  56863. */
  56864. GPUParticleSystem.prototype.reset = function () {
  56865. this._releaseBuffers();
  56866. this._releaseVAOs();
  56867. this._currentActiveCount = 0;
  56868. this._targetIndex = 0;
  56869. };
  56870. /**
  56871. * Returns the string "GPUParticleSystem"
  56872. * @returns a string containing the class name
  56873. */
  56874. GPUParticleSystem.prototype.getClassName = function () {
  56875. return "GPUParticleSystem";
  56876. };
  56877. Object.defineProperty(GPUParticleSystem.prototype, "isBillboardBased", {
  56878. /**
  56879. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  56880. */
  56881. get: function () {
  56882. return this._isBillboardBased;
  56883. },
  56884. set: function (value) {
  56885. if (this._isBillboardBased === value) {
  56886. return;
  56887. }
  56888. this._isBillboardBased = value;
  56889. this._releaseBuffers();
  56890. },
  56891. enumerable: true,
  56892. configurable: true
  56893. });
  56894. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  56895. var updateVertexBuffers = {};
  56896. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  56897. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  56898. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  56899. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  56900. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 3);
  56901. updateVertexBuffers["color"] = source.createVertexBuffer("color", 9, 4);
  56902. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 13, 3);
  56903. var offset = 16;
  56904. if (!this._isBillboardBased) {
  56905. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  56906. offset += 3;
  56907. }
  56908. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  56909. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  56910. this._engine.bindArrayBuffer(null);
  56911. return vao;
  56912. };
  56913. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  56914. var renderVertexBuffers = {};
  56915. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  56916. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  56917. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  56918. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 3, this._attributesStrideSize, true);
  56919. renderVertexBuffers["color"] = source.createVertexBuffer("color", 9, 4, this._attributesStrideSize, true);
  56920. var offset = 16;
  56921. if (!this._isBillboardBased) {
  56922. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  56923. offset += 3;
  56924. }
  56925. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2, this._attributesStrideSize, true);
  56926. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  56927. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  56928. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  56929. this._engine.bindArrayBuffer(null);
  56930. return vao;
  56931. };
  56932. GPUParticleSystem.prototype._initialize = function (force) {
  56933. if (force === void 0) { force = false; }
  56934. if (this._buffer0 && !force) {
  56935. return;
  56936. }
  56937. var engine = this._scene.getEngine();
  56938. var data = new Array();
  56939. if (!this.isBillboardBased) {
  56940. this._attributesStrideSize = 21;
  56941. }
  56942. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  56943. // position
  56944. data.push(0.0);
  56945. data.push(0.0);
  56946. data.push(0.0);
  56947. // Age and life
  56948. data.push(0.0); // create the particle as a dead one to create a new one at start
  56949. data.push(0.0);
  56950. // Seed
  56951. data.push(Math.random());
  56952. // Size
  56953. data.push(0.0);
  56954. data.push(0.0);
  56955. data.push(0.0);
  56956. // color
  56957. data.push(0.0);
  56958. data.push(0.0);
  56959. data.push(0.0);
  56960. data.push(0.0);
  56961. // direction
  56962. data.push(0.0);
  56963. data.push(0.0);
  56964. data.push(0.0);
  56965. if (!this.isBillboardBased) {
  56966. // initialDirection
  56967. data.push(0.0);
  56968. data.push(0.0);
  56969. data.push(0.0);
  56970. }
  56971. // angle
  56972. data.push(0.0);
  56973. data.push(0.0);
  56974. }
  56975. // Sprite data
  56976. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  56977. -0.5, 0.5, 0, 1,
  56978. -0.5, -0.5, 0, 0,
  56979. 0.5, -0.5, 1, 0]);
  56980. // Buffers
  56981. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  56982. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  56983. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  56984. // Update VAO
  56985. this._updateVAO = [];
  56986. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  56987. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  56988. // Render VAO
  56989. this._renderVAO = [];
  56990. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  56991. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  56992. // Links
  56993. this._sourceBuffer = this._buffer0;
  56994. this._targetBuffer = this._buffer1;
  56995. };
  56996. /** @hidden */
  56997. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  56998. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  56999. if (this._isBillboardBased) {
  57000. defines += "\n#define BILLBOARD";
  57001. }
  57002. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57003. return;
  57004. }
  57005. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"];
  57006. if (!this._isBillboardBased) {
  57007. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  57008. }
  57009. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  57010. this._updateEffectOptions.defines = defines;
  57011. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57012. };
  57013. /** @hidden */
  57014. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57015. var defines = "";
  57016. if (this._scene.clipPlane) {
  57017. defines = "\n#define CLIPPLANE";
  57018. }
  57019. if (this._isBillboardBased) {
  57020. defines += "\n#define BILLBOARD";
  57021. }
  57022. if (this._renderEffect && this._renderEffect.defines === defines) {
  57023. return;
  57024. }
  57025. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  57026. };
  57027. /**
  57028. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57029. */
  57030. GPUParticleSystem.prototype.animate = function () {
  57031. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  57032. this._actualFrame += this._timeDelta;
  57033. if (!this._stopped) {
  57034. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57035. this.stop();
  57036. }
  57037. }
  57038. };
  57039. /**
  57040. * Renders the particle system in its current state.
  57041. * @returns the current number of particles
  57042. */
  57043. GPUParticleSystem.prototype.render = function () {
  57044. if (!this._started) {
  57045. return 0;
  57046. }
  57047. this._recreateUpdateEffect();
  57048. this._recreateRenderEffect();
  57049. if (!this.isReady()) {
  57050. return 0;
  57051. }
  57052. if (this._currentRenderId === this._scene.getRenderId()) {
  57053. return 0;
  57054. }
  57055. this._currentRenderId = this._scene.getRenderId();
  57056. // Get everything ready to render
  57057. this._initialize();
  57058. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  57059. // Enable update effect
  57060. this._engine.enableEffect(this._updateEffect);
  57061. this._engine.setState(false);
  57062. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57063. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57064. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57065. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  57066. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57067. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57068. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57069. this._updateEffect.setDirectColor4("color1", this.color1);
  57070. this._updateEffect.setDirectColor4("color2", this.color2);
  57071. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57072. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  57073. this._updateEffect.setFloat2("angleRange", this.minAngularSpeed, this.maxAngularSpeed);
  57074. this._updateEffect.setVector3("gravity", this.gravity);
  57075. if (this.particleEmitterType) {
  57076. this.particleEmitterType.applyToShader(this._updateEffect);
  57077. }
  57078. var emitterWM;
  57079. if (this.emitter.position) {
  57080. var emitterMesh = this.emitter;
  57081. emitterWM = emitterMesh.getWorldMatrix();
  57082. }
  57083. else {
  57084. var emitterPosition = this.emitter;
  57085. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57086. }
  57087. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57088. // Bind source VAO
  57089. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57090. // Update
  57091. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57092. this._engine.setRasterizerState(false);
  57093. this._engine.beginTransformFeedback();
  57094. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57095. this._engine.endTransformFeedback();
  57096. this._engine.setRasterizerState(true);
  57097. this._engine.bindTransformFeedbackBuffer(null);
  57098. // Enable render effect
  57099. this._engine.enableEffect(this._renderEffect);
  57100. var viewMatrix = this._scene.getViewMatrix();
  57101. this._renderEffect.setMatrix("view", viewMatrix);
  57102. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57103. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57104. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57105. if (this._scene.clipPlane) {
  57106. var clipPlane = this._scene.clipPlane;
  57107. var invView = viewMatrix.clone();
  57108. invView.invert();
  57109. this._renderEffect.setMatrix("invView", invView);
  57110. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57111. }
  57112. // Draw order
  57113. switch (this.blendMode) {
  57114. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  57115. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  57116. break;
  57117. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  57118. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57119. break;
  57120. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  57121. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57122. break;
  57123. }
  57124. if (this.forceDepthWrite) {
  57125. this._engine.setDepthWrite(true);
  57126. }
  57127. // Bind source VAO
  57128. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57129. // Render
  57130. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57131. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57132. // Switch VAOs
  57133. this._targetIndex++;
  57134. if (this._targetIndex === 2) {
  57135. this._targetIndex = 0;
  57136. }
  57137. // Switch buffers
  57138. var tmpBuffer = this._sourceBuffer;
  57139. this._sourceBuffer = this._targetBuffer;
  57140. this._targetBuffer = tmpBuffer;
  57141. return this._currentActiveCount;
  57142. };
  57143. /**
  57144. * Rebuilds the particle system
  57145. */
  57146. GPUParticleSystem.prototype.rebuild = function () {
  57147. this._initialize(true);
  57148. };
  57149. GPUParticleSystem.prototype._releaseBuffers = function () {
  57150. if (this._buffer0) {
  57151. this._buffer0.dispose();
  57152. this._buffer0 = null;
  57153. }
  57154. if (this._buffer1) {
  57155. this._buffer1.dispose();
  57156. this._buffer1 = null;
  57157. }
  57158. if (this._spriteBuffer) {
  57159. this._spriteBuffer.dispose();
  57160. this._spriteBuffer = null;
  57161. }
  57162. };
  57163. GPUParticleSystem.prototype._releaseVAOs = function () {
  57164. if (!this._updateVAO) {
  57165. return;
  57166. }
  57167. for (var index = 0; index < this._updateVAO.length; index++) {
  57168. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57169. }
  57170. this._updateVAO = [];
  57171. for (var index = 0; index < this._renderVAO.length; index++) {
  57172. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57173. }
  57174. this._renderVAO = [];
  57175. };
  57176. /**
  57177. * Disposes the particle system and free the associated resources
  57178. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57179. */
  57180. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57181. if (disposeTexture === void 0) { disposeTexture = true; }
  57182. var index = this._scene.particleSystems.indexOf(this);
  57183. if (index > -1) {
  57184. this._scene.particleSystems.splice(index, 1);
  57185. }
  57186. this._releaseBuffers();
  57187. this._releaseVAOs();
  57188. if (this._randomTexture) {
  57189. this._randomTexture.dispose();
  57190. this._randomTexture = null;
  57191. }
  57192. if (disposeTexture && this.particleTexture) {
  57193. this.particleTexture.dispose();
  57194. this.particleTexture = null;
  57195. }
  57196. // Callback
  57197. this.onDisposeObservable.notifyObservers(this);
  57198. this.onDisposeObservable.clear();
  57199. };
  57200. /**
  57201. * Clones the particle system.
  57202. * @param name The name of the cloned object
  57203. * @param newEmitter The new emitter to use
  57204. * @returns the cloned particle system
  57205. */
  57206. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57207. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57208. BABYLON.Tools.DeepCopy(this, result);
  57209. if (newEmitter === undefined) {
  57210. newEmitter = this.emitter;
  57211. }
  57212. result.emitter = newEmitter;
  57213. if (this.particleTexture) {
  57214. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57215. }
  57216. return result;
  57217. };
  57218. /**
  57219. * Serializes the particle system to a JSON object.
  57220. * @returns the JSON object
  57221. */
  57222. GPUParticleSystem.prototype.serialize = function () {
  57223. var serializationObject = {};
  57224. serializationObject.name = this.name;
  57225. serializationObject.id = this.id;
  57226. // Emitter
  57227. if (this.emitter.position) {
  57228. var emitterMesh = this.emitter;
  57229. serializationObject.emitterId = emitterMesh.id;
  57230. }
  57231. else {
  57232. var emitterPosition = this.emitter;
  57233. serializationObject.emitter = emitterPosition.asArray();
  57234. }
  57235. serializationObject.capacity = this.getCapacity();
  57236. if (this.particleTexture) {
  57237. serializationObject.textureName = this.particleTexture.name;
  57238. }
  57239. // Animations
  57240. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57241. // Particle system
  57242. serializationObject.activeParticleCount = this.activeParticleCount;
  57243. serializationObject.randomTextureSize = this._randomTextureSize;
  57244. serializationObject.minSize = this.minSize;
  57245. serializationObject.maxSize = this.maxSize;
  57246. serializationObject.minEmitPower = this.minEmitPower;
  57247. serializationObject.maxEmitPower = this.maxEmitPower;
  57248. serializationObject.minLifeTime = this.minLifeTime;
  57249. serializationObject.maxLifeTime = this.maxLifeTime;
  57250. serializationObject.minAngularSpeed = this.minAngularSpeed;
  57251. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  57252. serializationObject.emitRate = this.emitRate;
  57253. serializationObject.gravity = this.gravity.asArray();
  57254. serializationObject.color1 = this.color1.asArray();
  57255. serializationObject.color2 = this.color2.asArray();
  57256. serializationObject.colorDead = this.colorDead.asArray();
  57257. serializationObject.updateSpeed = this.updateSpeed;
  57258. serializationObject.targetStopDuration = this.targetStopDuration;
  57259. serializationObject.blendMode = this.blendMode;
  57260. // Emitter
  57261. if (this.particleEmitterType) {
  57262. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57263. }
  57264. return serializationObject;
  57265. };
  57266. /**
  57267. * Parses a JSON object to create a GPU particle system.
  57268. * @param parsedParticleSystem The JSON object to parse
  57269. * @param scene The scene to create the particle system in
  57270. * @param rootUrl The root url to use to load external dependencies like texture
  57271. * @returns the parsed GPU particle system
  57272. */
  57273. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57274. var name = parsedParticleSystem.name;
  57275. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57276. if (parsedParticleSystem.id) {
  57277. particleSystem.id = parsedParticleSystem.id;
  57278. }
  57279. // Texture
  57280. if (parsedParticleSystem.textureName) {
  57281. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57282. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57283. }
  57284. // Emitter
  57285. if (parsedParticleSystem.emitterId) {
  57286. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57287. }
  57288. else {
  57289. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57290. }
  57291. // Animations
  57292. if (parsedParticleSystem.animations) {
  57293. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57294. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57295. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57296. }
  57297. }
  57298. // Particle system
  57299. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57300. particleSystem.minSize = parsedParticleSystem.minSize;
  57301. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57302. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57303. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57304. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  57305. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  57306. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57307. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57308. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57309. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57310. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57311. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57312. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57313. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57314. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57315. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57316. // Emitter
  57317. if (parsedParticleSystem.particleEmitterType) {
  57318. var emitterType = void 0;
  57319. switch (parsedParticleSystem.particleEmitterType.type) {
  57320. case "SphereEmitter":
  57321. emitterType = new BABYLON.SphereParticleEmitter();
  57322. break;
  57323. case "SphereDirectedParticleEmitter":
  57324. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57325. break;
  57326. case "ConeEmitter":
  57327. emitterType = new BABYLON.ConeParticleEmitter();
  57328. break;
  57329. case "BoxEmitter":
  57330. default:
  57331. emitterType = new BABYLON.BoxParticleEmitter();
  57332. break;
  57333. }
  57334. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57335. particleSystem.particleEmitterType = emitterType;
  57336. }
  57337. return particleSystem;
  57338. };
  57339. return GPUParticleSystem;
  57340. }());
  57341. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57342. })(BABYLON || (BABYLON = {}));
  57343. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57344. var BABYLON;
  57345. (function (BABYLON) {
  57346. /**
  57347. * Represents one particle of a solid particle system.
  57348. */
  57349. var SolidParticle = /** @class */ (function () {
  57350. /**
  57351. * Creates a Solid Particle object.
  57352. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57353. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57354. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57355. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57356. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57357. * @param shapeId (integer) is the model shape identifier in the SPS.
  57358. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57359. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57360. */
  57361. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57362. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57363. /**
  57364. * particle global index
  57365. */
  57366. this.idx = 0;
  57367. /**
  57368. * The color of the particle
  57369. */
  57370. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57371. /**
  57372. * The world space position of the particle.
  57373. */
  57374. this.position = BABYLON.Vector3.Zero();
  57375. /**
  57376. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57377. */
  57378. this.rotation = BABYLON.Vector3.Zero();
  57379. /**
  57380. * The scaling of the particle.
  57381. */
  57382. this.scaling = BABYLON.Vector3.One();
  57383. /**
  57384. * The uvs of the particle.
  57385. */
  57386. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57387. /**
  57388. * The current speed of the particle.
  57389. */
  57390. this.velocity = BABYLON.Vector3.Zero();
  57391. /**
  57392. * The pivot point in the particle local space.
  57393. */
  57394. this.pivot = BABYLON.Vector3.Zero();
  57395. /**
  57396. * Must the particle be translated from its pivot point in its local space ?
  57397. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57398. * Default : false
  57399. */
  57400. this.translateFromPivot = false;
  57401. /**
  57402. * Is the particle active or not ?
  57403. */
  57404. this.alive = true;
  57405. /**
  57406. * Is the particle visible or not ?
  57407. */
  57408. this.isVisible = true;
  57409. /**
  57410. * Index of this particle in the global "positions" array (Internal use)
  57411. */
  57412. this._pos = 0;
  57413. /**
  57414. * Index of this particle in the global "indices" array (Internal use)
  57415. */
  57416. this._ind = 0;
  57417. /**
  57418. * ModelShape id of this particle
  57419. */
  57420. this.shapeId = 0;
  57421. /**
  57422. * Index of the particle in its shape id (Internal use)
  57423. */
  57424. this.idxInShape = 0;
  57425. /**
  57426. * Still set as invisible in order to skip useless computations (Internal use)
  57427. */
  57428. this._stillInvisible = false;
  57429. /**
  57430. * Last computed particle rotation matrix
  57431. */
  57432. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  57433. /**
  57434. * Parent particle Id, if any.
  57435. * Default null.
  57436. */
  57437. this.parentId = null;
  57438. /**
  57439. * Internal global position in the SPS.
  57440. */
  57441. this._globalPosition = BABYLON.Vector3.Zero();
  57442. this.idx = particleIndex;
  57443. this._pos = positionIndex;
  57444. this._ind = indiceIndex;
  57445. this._model = model;
  57446. this.shapeId = shapeId;
  57447. this.idxInShape = idxInShape;
  57448. this._sps = sps;
  57449. if (modelBoundingInfo) {
  57450. this._modelBoundingInfo = modelBoundingInfo;
  57451. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  57452. }
  57453. }
  57454. Object.defineProperty(SolidParticle.prototype, "scale", {
  57455. /**
  57456. * Legacy support, changed scale to scaling
  57457. */
  57458. get: function () {
  57459. return this.scaling;
  57460. },
  57461. /**
  57462. * Legacy support, changed scale to scaling
  57463. */
  57464. set: function (scale) {
  57465. this.scaling = scale;
  57466. },
  57467. enumerable: true,
  57468. configurable: true
  57469. });
  57470. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  57471. /**
  57472. * Legacy support, changed quaternion to rotationQuaternion
  57473. */
  57474. get: function () {
  57475. return this.rotationQuaternion;
  57476. },
  57477. /**
  57478. * Legacy support, changed quaternion to rotationQuaternion
  57479. */
  57480. set: function (q) {
  57481. this.rotationQuaternion = q;
  57482. },
  57483. enumerable: true,
  57484. configurable: true
  57485. });
  57486. /**
  57487. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  57488. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  57489. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  57490. * @returns true if it intersects
  57491. */
  57492. SolidParticle.prototype.intersectsMesh = function (target) {
  57493. if (!this._boundingInfo || !target._boundingInfo) {
  57494. return false;
  57495. }
  57496. if (this._sps._bSphereOnly) {
  57497. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  57498. }
  57499. return this._boundingInfo.intersects(target._boundingInfo, false);
  57500. };
  57501. return SolidParticle;
  57502. }());
  57503. BABYLON.SolidParticle = SolidParticle;
  57504. /**
  57505. * Represents the shape of the model used by one particle of a solid particle system.
  57506. * SPS internal tool, don't use it manually.
  57507. */
  57508. var ModelShape = /** @class */ (function () {
  57509. /**
  57510. * 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.
  57511. * SPS internal tool, don't use it manually.
  57512. * @hidden
  57513. */
  57514. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  57515. /**
  57516. * length of the shape in the model indices array (internal use)
  57517. */
  57518. this._indicesLength = 0;
  57519. this.shapeID = id;
  57520. this._shape = shape;
  57521. this._indicesLength = indicesLength;
  57522. this._shapeUV = shapeUV;
  57523. this._positionFunction = posFunction;
  57524. this._vertexFunction = vtxFunction;
  57525. }
  57526. return ModelShape;
  57527. }());
  57528. BABYLON.ModelShape = ModelShape;
  57529. /**
  57530. * Represents a Depth Sorted Particle in the solid particle system.
  57531. */
  57532. var DepthSortedParticle = /** @class */ (function () {
  57533. function DepthSortedParticle() {
  57534. /**
  57535. * Index of the particle in the "indices" array
  57536. */
  57537. this.ind = 0;
  57538. /**
  57539. * Length of the particle shape in the "indices" array
  57540. */
  57541. this.indicesLength = 0;
  57542. /**
  57543. * Squared distance from the particle to the camera
  57544. */
  57545. this.sqDistance = 0.0;
  57546. }
  57547. return DepthSortedParticle;
  57548. }());
  57549. BABYLON.DepthSortedParticle = DepthSortedParticle;
  57550. })(BABYLON || (BABYLON = {}));
  57551. //# sourceMappingURL=babylon.solidParticle.js.map
  57552. var BABYLON;
  57553. (function (BABYLON) {
  57554. /**
  57555. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  57556. *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.
  57557. * The SPS is also a particle system. It provides some methods to manage the particles.
  57558. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  57559. *
  57560. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  57561. */
  57562. var SolidParticleSystem = /** @class */ (function () {
  57563. /**
  57564. * Creates a SPS (Solid Particle System) object.
  57565. * @param name (String) is the SPS name, this will be the underlying mesh name.
  57566. * @param scene (Scene) is the scene in which the SPS is added.
  57567. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  57568. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  57569. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  57570. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  57571. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  57572. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  57573. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  57574. */
  57575. function SolidParticleSystem(name, scene, options) {
  57576. /**
  57577. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  57578. * Example : var p = SPS.particles[i];
  57579. */
  57580. this.particles = new Array();
  57581. /**
  57582. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  57583. */
  57584. this.nbParticles = 0;
  57585. /**
  57586. * If the particles must ever face the camera (default false). Useful for planar particles.
  57587. */
  57588. this.billboard = false;
  57589. /**
  57590. * Recompute normals when adding a shape
  57591. */
  57592. this.recomputeNormals = true;
  57593. /**
  57594. * This a counter ofr your own usage. It's not set by any SPS functions.
  57595. */
  57596. this.counter = 0;
  57597. /**
  57598. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  57599. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  57600. */
  57601. this.vars = {};
  57602. /**
  57603. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  57604. */
  57605. this._bSphereOnly = false;
  57606. /**
  57607. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  57608. */
  57609. this._bSphereRadiusFactor = 1.0;
  57610. this._positions = new Array();
  57611. this._indices = new Array();
  57612. this._normals = new Array();
  57613. this._colors = new Array();
  57614. this._uvs = new Array();
  57615. this._index = 0; // indices index
  57616. this._updatable = true;
  57617. this._pickable = false;
  57618. this._isVisibilityBoxLocked = false;
  57619. this._alwaysVisible = false;
  57620. this._depthSort = false;
  57621. this._shapeCounter = 0;
  57622. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  57623. this._color = new BABYLON.Color4(0, 0, 0, 0);
  57624. this._computeParticleColor = true;
  57625. this._computeParticleTexture = true;
  57626. this._computeParticleRotation = true;
  57627. this._computeParticleVertex = false;
  57628. this._computeBoundingBox = false;
  57629. this._depthSortParticles = true;
  57630. this._cam_axisZ = BABYLON.Vector3.Zero();
  57631. this._cam_axisY = BABYLON.Vector3.Zero();
  57632. this._cam_axisX = BABYLON.Vector3.Zero();
  57633. this._axisZ = BABYLON.Axis.Z;
  57634. this._camDir = BABYLON.Vector3.Zero();
  57635. this._camInvertedPosition = BABYLON.Vector3.Zero();
  57636. this._rotMatrix = new BABYLON.Matrix();
  57637. this._invertMatrix = new BABYLON.Matrix();
  57638. this._rotated = BABYLON.Vector3.Zero();
  57639. this._quaternion = new BABYLON.Quaternion();
  57640. this._vertex = BABYLON.Vector3.Zero();
  57641. this._normal = BABYLON.Vector3.Zero();
  57642. this._yaw = 0.0;
  57643. this._pitch = 0.0;
  57644. this._roll = 0.0;
  57645. this._halfroll = 0.0;
  57646. this._halfpitch = 0.0;
  57647. this._halfyaw = 0.0;
  57648. this._sinRoll = 0.0;
  57649. this._cosRoll = 0.0;
  57650. this._sinPitch = 0.0;
  57651. this._cosPitch = 0.0;
  57652. this._sinYaw = 0.0;
  57653. this._cosYaw = 0.0;
  57654. this._mustUnrotateFixedNormals = false;
  57655. this._minimum = BABYLON.Vector3.Zero();
  57656. this._maximum = BABYLON.Vector3.Zero();
  57657. this._minBbox = BABYLON.Vector3.Zero();
  57658. this._maxBbox = BABYLON.Vector3.Zero();
  57659. this._particlesIntersect = false;
  57660. this._depthSortFunction = function (p1, p2) {
  57661. return (p2.sqDistance - p1.sqDistance);
  57662. };
  57663. this._needs32Bits = false;
  57664. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  57665. this._scaledPivot = BABYLON.Vector3.Zero();
  57666. this._particleHasParent = false;
  57667. this.name = name;
  57668. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57669. this._camera = scene.activeCamera;
  57670. this._pickable = options ? options.isPickable : false;
  57671. this._depthSort = options ? options.enableDepthSort : false;
  57672. this._particlesIntersect = options ? options.particleIntersection : false;
  57673. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  57674. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  57675. if (options && options.updatable !== undefined) {
  57676. this._updatable = options.updatable;
  57677. }
  57678. else {
  57679. this._updatable = true;
  57680. }
  57681. if (this._pickable) {
  57682. this.pickedParticles = [];
  57683. }
  57684. if (this._depthSort) {
  57685. this.depthSortedParticles = [];
  57686. }
  57687. }
  57688. /**
  57689. * Builds the SPS underlying mesh. Returns a standard Mesh.
  57690. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  57691. * @returns the created mesh
  57692. */
  57693. SolidParticleSystem.prototype.buildMesh = function () {
  57694. if (this.nbParticles === 0) {
  57695. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  57696. this.addShape(triangle, 1);
  57697. triangle.dispose();
  57698. }
  57699. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  57700. this._positions32 = new Float32Array(this._positions);
  57701. this._uvs32 = new Float32Array(this._uvs);
  57702. this._colors32 = new Float32Array(this._colors);
  57703. if (this.recomputeNormals) {
  57704. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  57705. }
  57706. this._normals32 = new Float32Array(this._normals);
  57707. this._fixedNormal32 = new Float32Array(this._normals);
  57708. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  57709. this._unrotateFixedNormals();
  57710. }
  57711. var vertexData = new BABYLON.VertexData();
  57712. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  57713. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  57714. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  57715. if (this._uvs32.length > 0) {
  57716. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  57717. }
  57718. if (this._colors32.length > 0) {
  57719. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  57720. }
  57721. var mesh = new BABYLON.Mesh(this.name, this._scene);
  57722. vertexData.applyToMesh(mesh, this._updatable);
  57723. this.mesh = mesh;
  57724. this.mesh.isPickable = this._pickable;
  57725. // free memory
  57726. if (!this._depthSort) {
  57727. this._indices = null;
  57728. }
  57729. this._positions = null;
  57730. this._normals = null;
  57731. this._uvs = null;
  57732. this._colors = null;
  57733. if (!this._updatable) {
  57734. this.particles.length = 0;
  57735. }
  57736. return mesh;
  57737. };
  57738. /**
  57739. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  57740. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  57741. * Thus the particles generated from `digest()` have their property `position` set yet.
  57742. * @param mesh ( Mesh ) is the mesh to be digested
  57743. * @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
  57744. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  57745. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  57746. * @returns the current SPS
  57747. */
  57748. SolidParticleSystem.prototype.digest = function (mesh, options) {
  57749. var size = (options && options.facetNb) || 1;
  57750. var number = (options && options.number) || 0;
  57751. var delta = (options && options.delta) || 0;
  57752. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57753. var meshInd = mesh.getIndices();
  57754. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57755. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57756. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57757. var f = 0; // facet counter
  57758. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  57759. // compute size from number
  57760. if (number) {
  57761. number = (number > totalFacets) ? totalFacets : number;
  57762. size = Math.round(totalFacets / number);
  57763. delta = 0;
  57764. }
  57765. else {
  57766. size = (size > totalFacets) ? totalFacets : size;
  57767. }
  57768. var facetPos = []; // submesh positions
  57769. var facetInd = []; // submesh indices
  57770. var facetUV = []; // submesh UV
  57771. var facetCol = []; // submesh colors
  57772. var barycenter = BABYLON.Vector3.Zero();
  57773. var sizeO = size;
  57774. while (f < totalFacets) {
  57775. size = sizeO + Math.floor((1 + delta) * Math.random());
  57776. if (f > totalFacets - size) {
  57777. size = totalFacets - f;
  57778. }
  57779. // reset temp arrays
  57780. facetPos.length = 0;
  57781. facetInd.length = 0;
  57782. facetUV.length = 0;
  57783. facetCol.length = 0;
  57784. // iterate over "size" facets
  57785. var fi = 0;
  57786. for (var j = f * 3; j < (f + size) * 3; j++) {
  57787. facetInd.push(fi);
  57788. var i = meshInd[j];
  57789. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  57790. if (meshUV) {
  57791. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  57792. }
  57793. if (meshCol) {
  57794. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  57795. }
  57796. fi++;
  57797. }
  57798. // create a model shape for each single particle
  57799. var idx = this.nbParticles;
  57800. var shape = this._posToShape(facetPos);
  57801. var shapeUV = this._uvsToShapeUV(facetUV);
  57802. // compute the barycenter of the shape
  57803. var v;
  57804. for (v = 0; v < shape.length; v++) {
  57805. barycenter.addInPlace(shape[v]);
  57806. }
  57807. barycenter.scaleInPlace(1 / shape.length);
  57808. // shift the shape from its barycenter to the origin
  57809. for (v = 0; v < shape.length; v++) {
  57810. shape[v].subtractInPlace(barycenter);
  57811. }
  57812. var bInfo;
  57813. if (this._particlesIntersect) {
  57814. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  57815. }
  57816. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  57817. // add the particle in the SPS
  57818. var currentPos = this._positions.length;
  57819. var currentInd = this._indices.length;
  57820. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  57821. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  57822. // initialize the particle position
  57823. this.particles[this.nbParticles].position.addInPlace(barycenter);
  57824. this._index += shape.length;
  57825. idx++;
  57826. this.nbParticles++;
  57827. this._shapeCounter++;
  57828. f += size;
  57829. }
  57830. return this;
  57831. };
  57832. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  57833. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  57834. var index = 0;
  57835. var idx = 0;
  57836. for (var p = 0; p < this.particles.length; p++) {
  57837. this._particle = this.particles[p];
  57838. this._shape = this._particle._model._shape;
  57839. if (this._particle.rotationQuaternion) {
  57840. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  57841. }
  57842. else {
  57843. this._yaw = this._particle.rotation.y;
  57844. this._pitch = this._particle.rotation.x;
  57845. this._roll = this._particle.rotation.z;
  57846. this._quaternionRotationYPR();
  57847. }
  57848. this._quaternionToRotationMatrix();
  57849. this._rotMatrix.invertToRef(this._invertMatrix);
  57850. for (var pt = 0; pt < this._shape.length; pt++) {
  57851. idx = index + pt * 3;
  57852. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  57853. this._fixedNormal32[idx] = this._normal.x;
  57854. this._fixedNormal32[idx + 1] = this._normal.y;
  57855. this._fixedNormal32[idx + 2] = this._normal.z;
  57856. }
  57857. index = idx + 3;
  57858. }
  57859. };
  57860. //reset copy
  57861. SolidParticleSystem.prototype._resetCopy = function () {
  57862. this._copy.position.x = 0;
  57863. this._copy.position.y = 0;
  57864. this._copy.position.z = 0;
  57865. this._copy.rotation.x = 0;
  57866. this._copy.rotation.y = 0;
  57867. this._copy.rotation.z = 0;
  57868. this._copy.rotationQuaternion = null;
  57869. this._copy.scaling.x = 1.0;
  57870. this._copy.scaling.y = 1.0;
  57871. this._copy.scaling.z = 1.0;
  57872. this._copy.uvs.x = 0;
  57873. this._copy.uvs.y = 0;
  57874. this._copy.uvs.z = 1.0;
  57875. this._copy.uvs.w = 1.0;
  57876. this._copy.color = null;
  57877. this._copy.translateFromPivot = false;
  57878. };
  57879. // _meshBuilder : inserts the shape model in the global SPS mesh
  57880. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  57881. var i;
  57882. var u = 0;
  57883. var c = 0;
  57884. var n = 0;
  57885. this._resetCopy();
  57886. if (options && options.positionFunction) { // call to custom positionFunction
  57887. options.positionFunction(this._copy, idx, idxInShape);
  57888. this._mustUnrotateFixedNormals = true;
  57889. }
  57890. if (this._copy.rotationQuaternion) {
  57891. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57892. }
  57893. else {
  57894. this._yaw = this._copy.rotation.y;
  57895. this._pitch = this._copy.rotation.x;
  57896. this._roll = this._copy.rotation.z;
  57897. this._quaternionRotationYPR();
  57898. }
  57899. this._quaternionToRotationMatrix();
  57900. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  57901. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  57902. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  57903. if (this._copy.translateFromPivot) {
  57904. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  57905. }
  57906. else {
  57907. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  57908. }
  57909. for (i = 0; i < shape.length; i++) {
  57910. this._vertex.x = shape[i].x;
  57911. this._vertex.y = shape[i].y;
  57912. this._vertex.z = shape[i].z;
  57913. if (options && options.vertexFunction) {
  57914. options.vertexFunction(this._copy, this._vertex, i);
  57915. }
  57916. this._vertex.x *= this._copy.scaling.x;
  57917. this._vertex.y *= this._copy.scaling.y;
  57918. this._vertex.z *= this._copy.scaling.z;
  57919. this._vertex.x -= this._scaledPivot.x;
  57920. this._vertex.y -= this._scaledPivot.y;
  57921. this._vertex.z -= this._scaledPivot.z;
  57922. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57923. this._rotated.addInPlace(this._pivotBackTranslation);
  57924. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  57925. if (meshUV) {
  57926. 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);
  57927. u += 2;
  57928. }
  57929. if (this._copy.color) {
  57930. this._color = this._copy.color;
  57931. }
  57932. else if (meshCol && meshCol[c] !== undefined) {
  57933. this._color.r = meshCol[c];
  57934. this._color.g = meshCol[c + 1];
  57935. this._color.b = meshCol[c + 2];
  57936. this._color.a = meshCol[c + 3];
  57937. }
  57938. else {
  57939. this._color.r = 1.0;
  57940. this._color.g = 1.0;
  57941. this._color.b = 1.0;
  57942. this._color.a = 1.0;
  57943. }
  57944. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  57945. c += 4;
  57946. if (!this.recomputeNormals && meshNor) {
  57947. this._normal.x = meshNor[n];
  57948. this._normal.y = meshNor[n + 1];
  57949. this._normal.z = meshNor[n + 2];
  57950. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  57951. normals.push(this._normal.x, this._normal.y, this._normal.z);
  57952. n += 3;
  57953. }
  57954. }
  57955. for (i = 0; i < meshInd.length; i++) {
  57956. var current_ind = p + meshInd[i];
  57957. indices.push(current_ind);
  57958. if (current_ind > 65535) {
  57959. this._needs32Bits = true;
  57960. }
  57961. }
  57962. if (this._pickable) {
  57963. var nbfaces = meshInd.length / 3;
  57964. for (i = 0; i < nbfaces; i++) {
  57965. this.pickedParticles.push({ idx: idx, faceId: i });
  57966. }
  57967. }
  57968. if (this._depthSort) {
  57969. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  57970. }
  57971. return this._copy;
  57972. };
  57973. // returns a shape array from positions array
  57974. SolidParticleSystem.prototype._posToShape = function (positions) {
  57975. var shape = [];
  57976. for (var i = 0; i < positions.length; i += 3) {
  57977. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  57978. }
  57979. return shape;
  57980. };
  57981. // returns a shapeUV array from a Vector4 uvs
  57982. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  57983. var shapeUV = [];
  57984. if (uvs) {
  57985. for (var i = 0; i < uvs.length; i++)
  57986. shapeUV.push(uvs[i]);
  57987. }
  57988. return shapeUV;
  57989. };
  57990. // adds a new particle object in the particles array
  57991. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  57992. if (bInfo === void 0) { bInfo = null; }
  57993. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  57994. this.particles.push(sp);
  57995. return sp;
  57996. };
  57997. /**
  57998. * Adds some particles to the SPS from the model shape. Returns the shape id.
  57999. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58000. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58001. * @param nb (positive integer) the number of particles to be created from this model
  58002. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58003. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58004. * @returns the number of shapes in the system
  58005. */
  58006. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58007. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58008. var meshInd = mesh.getIndices();
  58009. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58010. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58011. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58012. var bbInfo;
  58013. if (this._particlesIntersect) {
  58014. bbInfo = mesh.getBoundingInfo();
  58015. }
  58016. var shape = this._posToShape(meshPos);
  58017. var shapeUV = this._uvsToShapeUV(meshUV);
  58018. var posfunc = options ? options.positionFunction : null;
  58019. var vtxfunc = options ? options.vertexFunction : null;
  58020. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58021. // particles
  58022. var sp;
  58023. var currentCopy;
  58024. var idx = this.nbParticles;
  58025. for (var i = 0; i < nb; i++) {
  58026. var currentPos = this._positions.length;
  58027. var currentInd = this._indices.length;
  58028. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58029. if (this._updatable) {
  58030. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58031. sp.position.copyFrom(currentCopy.position);
  58032. sp.rotation.copyFrom(currentCopy.rotation);
  58033. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58034. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58035. }
  58036. if (currentCopy.color && sp.color) {
  58037. sp.color.copyFrom(currentCopy.color);
  58038. }
  58039. sp.scaling.copyFrom(currentCopy.scaling);
  58040. sp.uvs.copyFrom(currentCopy.uvs);
  58041. }
  58042. this._index += shape.length;
  58043. idx++;
  58044. }
  58045. this.nbParticles += nb;
  58046. this._shapeCounter++;
  58047. return this._shapeCounter - 1;
  58048. };
  58049. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58050. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58051. this._resetCopy();
  58052. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58053. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58054. }
  58055. if (this._copy.rotationQuaternion) {
  58056. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58057. }
  58058. else {
  58059. this._yaw = this._copy.rotation.y;
  58060. this._pitch = this._copy.rotation.x;
  58061. this._roll = this._copy.rotation.z;
  58062. this._quaternionRotationYPR();
  58063. }
  58064. this._quaternionToRotationMatrix();
  58065. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58066. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58067. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58068. if (this._copy.translateFromPivot) {
  58069. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58070. }
  58071. else {
  58072. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58073. }
  58074. this._shape = particle._model._shape;
  58075. for (var pt = 0; pt < this._shape.length; pt++) {
  58076. this._vertex.x = this._shape[pt].x;
  58077. this._vertex.y = this._shape[pt].y;
  58078. this._vertex.z = this._shape[pt].z;
  58079. if (particle._model._vertexFunction) {
  58080. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58081. }
  58082. this._vertex.x *= this._copy.scaling.x;
  58083. this._vertex.y *= this._copy.scaling.y;
  58084. this._vertex.z *= this._copy.scaling.z;
  58085. this._vertex.x -= this._scaledPivot.x;
  58086. this._vertex.y -= this._scaledPivot.y;
  58087. this._vertex.z -= this._scaledPivot.z;
  58088. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58089. this._rotated.addInPlace(this._pivotBackTranslation);
  58090. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58091. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58092. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58093. }
  58094. particle.position.x = 0.0;
  58095. particle.position.y = 0.0;
  58096. particle.position.z = 0.0;
  58097. particle.rotation.x = 0.0;
  58098. particle.rotation.y = 0.0;
  58099. particle.rotation.z = 0.0;
  58100. particle.rotationQuaternion = null;
  58101. particle.scaling.x = 1.0;
  58102. particle.scaling.y = 1.0;
  58103. particle.scaling.z = 1.0;
  58104. particle.uvs.x = 0.0;
  58105. particle.uvs.y = 0.0;
  58106. particle.uvs.z = 1.0;
  58107. particle.uvs.w = 1.0;
  58108. particle.pivot.x = 0.0;
  58109. particle.pivot.y = 0.0;
  58110. particle.pivot.z = 0.0;
  58111. particle.translateFromPivot = false;
  58112. particle.parentId = null;
  58113. };
  58114. /**
  58115. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58116. * @returns the SPS.
  58117. */
  58118. SolidParticleSystem.prototype.rebuildMesh = function () {
  58119. for (var p = 0; p < this.particles.length; p++) {
  58120. this._rebuildParticle(this.particles[p]);
  58121. }
  58122. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58123. return this;
  58124. };
  58125. /**
  58126. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58127. * This method calls `updateParticle()` for each particle of the SPS.
  58128. * For an animated SPS, it is usually called within the render loop.
  58129. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58130. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58131. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58132. * @returns the SPS.
  58133. */
  58134. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58135. if (start === void 0) { start = 0; }
  58136. if (end === void 0) { end = this.nbParticles - 1; }
  58137. if (update === void 0) { update = true; }
  58138. if (!this._updatable) {
  58139. return this;
  58140. }
  58141. // custom beforeUpdate
  58142. this.beforeUpdateParticles(start, end, update);
  58143. this._cam_axisX.x = 1.0;
  58144. this._cam_axisX.y = 0.0;
  58145. this._cam_axisX.z = 0.0;
  58146. this._cam_axisY.x = 0.0;
  58147. this._cam_axisY.y = 1.0;
  58148. this._cam_axisY.z = 0.0;
  58149. this._cam_axisZ.x = 0.0;
  58150. this._cam_axisZ.y = 0.0;
  58151. this._cam_axisZ.z = 1.0;
  58152. // cases when the World Matrix is to be computed first
  58153. if (this.billboard || this._depthSort) {
  58154. this.mesh.computeWorldMatrix(true);
  58155. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58156. }
  58157. // if the particles will always face the camera
  58158. if (this.billboard) {
  58159. // compute the camera position and un-rotate it by the current mesh rotation
  58160. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58161. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58162. this._cam_axisZ.normalize();
  58163. // same for camera up vector extracted from the cam view matrix
  58164. var view = this._camera.getViewMatrix(true);
  58165. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58166. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58167. this._cam_axisY.normalize();
  58168. this._cam_axisX.normalize();
  58169. }
  58170. // if depthSort, compute the camera global position in the mesh local system
  58171. if (this._depthSort) {
  58172. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58173. }
  58174. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58175. var idx = 0; // current position index in the global array positions32
  58176. var index = 0; // position start index in the global array positions32 of the current particle
  58177. var colidx = 0; // current color index in the global array colors32
  58178. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58179. var uvidx = 0; // current uv index in the global array uvs32
  58180. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58181. var pt = 0; // current index in the particle model shape
  58182. if (this.mesh.isFacetDataEnabled) {
  58183. this._computeBoundingBox = true;
  58184. }
  58185. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58186. if (this._computeBoundingBox) {
  58187. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58188. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58189. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58190. }
  58191. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58192. if (this.mesh._boundingInfo) {
  58193. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58194. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58195. }
  58196. }
  58197. }
  58198. // particle loop
  58199. index = this.particles[start]._pos;
  58200. var vpos = (index / 3) | 0;
  58201. colorIndex = vpos * 4;
  58202. uvIndex = vpos * 2;
  58203. for (var p = start; p <= end; p++) {
  58204. this._particle = this.particles[p];
  58205. this._shape = this._particle._model._shape;
  58206. this._shapeUV = this._particle._model._shapeUV;
  58207. // call to custom user function to update the particle properties
  58208. this.updateParticle(this._particle);
  58209. // camera-particle distance for depth sorting
  58210. if (this._depthSort && this._depthSortParticles) {
  58211. var dsp = this.depthSortedParticles[p];
  58212. dsp.ind = this._particle._ind;
  58213. dsp.indicesLength = this._particle._model._indicesLength;
  58214. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58215. }
  58216. // skip the computations for inactive or already invisible particles
  58217. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58218. // increment indexes for the next particle
  58219. pt = this._shape.length;
  58220. index += pt * 3;
  58221. colorIndex += pt * 4;
  58222. uvIndex += pt * 2;
  58223. continue;
  58224. }
  58225. if (this._particle.isVisible) {
  58226. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58227. this._particleHasParent = (this._particle.parentId !== null);
  58228. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58229. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58230. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58231. // particle rotation matrix
  58232. if (this.billboard) {
  58233. this._particle.rotation.x = 0.0;
  58234. this._particle.rotation.y = 0.0;
  58235. }
  58236. if (this._computeParticleRotation || this.billboard) {
  58237. if (this._particle.rotationQuaternion) {
  58238. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58239. }
  58240. else {
  58241. this._yaw = this._particle.rotation.y;
  58242. this._pitch = this._particle.rotation.x;
  58243. this._roll = this._particle.rotation.z;
  58244. this._quaternionRotationYPR();
  58245. }
  58246. this._quaternionToRotationMatrix();
  58247. }
  58248. if (this._particleHasParent) {
  58249. this._parent = this.particles[this._particle.parentId];
  58250. 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];
  58251. 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];
  58252. 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];
  58253. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58254. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58255. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58256. if (this._computeParticleRotation || this.billboard) {
  58257. 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];
  58258. 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];
  58259. 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];
  58260. 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];
  58261. 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];
  58262. 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];
  58263. 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];
  58264. 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];
  58265. 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];
  58266. }
  58267. }
  58268. else {
  58269. this._particle._globalPosition.x = this._particle.position.x;
  58270. this._particle._globalPosition.y = this._particle.position.y;
  58271. this._particle._globalPosition.z = this._particle.position.z;
  58272. if (this._computeParticleRotation || this.billboard) {
  58273. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58274. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58275. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58276. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58277. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58278. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58279. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58280. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58281. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58282. }
  58283. }
  58284. if (this._particle.translateFromPivot) {
  58285. this._pivotBackTranslation.x = 0.0;
  58286. this._pivotBackTranslation.y = 0.0;
  58287. this._pivotBackTranslation.z = 0.0;
  58288. }
  58289. else {
  58290. this._pivotBackTranslation.x = this._scaledPivot.x;
  58291. this._pivotBackTranslation.y = this._scaledPivot.y;
  58292. this._pivotBackTranslation.z = this._scaledPivot.z;
  58293. }
  58294. // particle vertex loop
  58295. for (pt = 0; pt < this._shape.length; pt++) {
  58296. idx = index + pt * 3;
  58297. colidx = colorIndex + pt * 4;
  58298. uvidx = uvIndex + pt * 2;
  58299. this._vertex.x = this._shape[pt].x;
  58300. this._vertex.y = this._shape[pt].y;
  58301. this._vertex.z = this._shape[pt].z;
  58302. if (this._computeParticleVertex) {
  58303. this.updateParticleVertex(this._particle, this._vertex, pt);
  58304. }
  58305. // positions
  58306. this._vertex.x *= this._particle.scaling.x;
  58307. this._vertex.y *= this._particle.scaling.y;
  58308. this._vertex.z *= this._particle.scaling.z;
  58309. this._vertex.x -= this._scaledPivot.x;
  58310. this._vertex.y -= this._scaledPivot.y;
  58311. this._vertex.z -= this._scaledPivot.z;
  58312. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58313. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58314. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58315. this._rotated.x += this._pivotBackTranslation.x;
  58316. this._rotated.y += this._pivotBackTranslation.y;
  58317. this._rotated.z += this._pivotBackTranslation.z;
  58318. 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;
  58319. 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;
  58320. 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;
  58321. if (this._computeBoundingBox) {
  58322. if (this._positions32[idx] < this._minimum.x) {
  58323. this._minimum.x = this._positions32[idx];
  58324. }
  58325. if (this._positions32[idx] > this._maximum.x) {
  58326. this._maximum.x = this._positions32[idx];
  58327. }
  58328. if (this._positions32[idx + 1] < this._minimum.y) {
  58329. this._minimum.y = this._positions32[idx + 1];
  58330. }
  58331. if (this._positions32[idx + 1] > this._maximum.y) {
  58332. this._maximum.y = this._positions32[idx + 1];
  58333. }
  58334. if (this._positions32[idx + 2] < this._minimum.z) {
  58335. this._minimum.z = this._positions32[idx + 2];
  58336. }
  58337. if (this._positions32[idx + 2] > this._maximum.z) {
  58338. this._maximum.z = this._positions32[idx + 2];
  58339. }
  58340. }
  58341. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58342. if (!this._computeParticleVertex) {
  58343. this._normal.x = this._fixedNormal32[idx];
  58344. this._normal.y = this._fixedNormal32[idx + 1];
  58345. this._normal.z = this._fixedNormal32[idx + 2];
  58346. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58347. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58348. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58349. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58350. 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;
  58351. 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;
  58352. }
  58353. if (this._computeParticleColor && this._particle.color) {
  58354. this._colors32[colidx] = this._particle.color.r;
  58355. this._colors32[colidx + 1] = this._particle.color.g;
  58356. this._colors32[colidx + 2] = this._particle.color.b;
  58357. this._colors32[colidx + 3] = this._particle.color.a;
  58358. }
  58359. if (this._computeParticleTexture) {
  58360. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58361. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58362. }
  58363. }
  58364. }
  58365. // particle just set invisible : scaled to zero and positioned at the origin
  58366. else {
  58367. this._particle._stillInvisible = true; // mark the particle as invisible
  58368. for (pt = 0; pt < this._shape.length; pt++) {
  58369. idx = index + pt * 3;
  58370. colidx = colorIndex + pt * 4;
  58371. uvidx = uvIndex + pt * 2;
  58372. this._positions32[idx] = 0.0;
  58373. this._positions32[idx + 1] = 0.0;
  58374. this._positions32[idx + 2] = 0.0;
  58375. this._normals32[idx] = 0.0;
  58376. this._normals32[idx + 1] = 0.0;
  58377. this._normals32[idx + 2] = 0.0;
  58378. if (this._computeParticleColor && this._particle.color) {
  58379. this._colors32[colidx] = this._particle.color.r;
  58380. this._colors32[colidx + 1] = this._particle.color.g;
  58381. this._colors32[colidx + 2] = this._particle.color.b;
  58382. this._colors32[colidx + 3] = this._particle.color.a;
  58383. }
  58384. if (this._computeParticleTexture) {
  58385. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58386. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58387. }
  58388. }
  58389. }
  58390. // if the particle intersections must be computed : update the bbInfo
  58391. if (this._particlesIntersect) {
  58392. var bInfo = this._particle._boundingInfo;
  58393. var bBox = bInfo.boundingBox;
  58394. var bSphere = bInfo.boundingSphere;
  58395. if (!this._bSphereOnly) {
  58396. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58397. for (var b = 0; b < bBox.vectors.length; b++) {
  58398. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58399. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  58400. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  58401. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58402. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58403. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58404. 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;
  58405. 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;
  58406. 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;
  58407. }
  58408. bBox._update(this.mesh._worldMatrix);
  58409. }
  58410. // place and scale the particle bouding sphere in the SPS local system, then update it
  58411. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  58412. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  58413. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  58414. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  58415. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  58416. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  58417. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  58418. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  58419. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  58420. 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));
  58421. bSphere._update(this.mesh._worldMatrix);
  58422. }
  58423. // increment indexes for the next particle
  58424. index = idx + 3;
  58425. colorIndex = colidx + 4;
  58426. uvIndex = uvidx + 2;
  58427. }
  58428. // if the VBO must be updated
  58429. if (update) {
  58430. if (this._computeParticleColor) {
  58431. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58432. }
  58433. if (this._computeParticleTexture) {
  58434. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58435. }
  58436. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58437. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  58438. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  58439. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  58440. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  58441. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  58442. for (var i = 0; i < this._normals32.length; i++) {
  58443. this._fixedNormal32[i] = this._normals32[i];
  58444. }
  58445. }
  58446. if (!this.mesh.areNormalsFrozen) {
  58447. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  58448. }
  58449. }
  58450. if (this._depthSort && this._depthSortParticles) {
  58451. this.depthSortedParticles.sort(this._depthSortFunction);
  58452. var dspl = this.depthSortedParticles.length;
  58453. var sorted = 0;
  58454. var lind = 0;
  58455. var sind = 0;
  58456. var sid = 0;
  58457. for (sorted = 0; sorted < dspl; sorted++) {
  58458. lind = this.depthSortedParticles[sorted].indicesLength;
  58459. sind = this.depthSortedParticles[sorted].ind;
  58460. for (var i = 0; i < lind; i++) {
  58461. this._indices32[sid] = this._indices[sind + i];
  58462. sid++;
  58463. }
  58464. }
  58465. this.mesh.updateIndices(this._indices32);
  58466. }
  58467. }
  58468. if (this._computeBoundingBox) {
  58469. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  58470. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  58471. }
  58472. this.afterUpdateParticles(start, end, update);
  58473. return this;
  58474. };
  58475. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  58476. this._halfroll = this._roll * 0.5;
  58477. this._halfpitch = this._pitch * 0.5;
  58478. this._halfyaw = this._yaw * 0.5;
  58479. this._sinRoll = Math.sin(this._halfroll);
  58480. this._cosRoll = Math.cos(this._halfroll);
  58481. this._sinPitch = Math.sin(this._halfpitch);
  58482. this._cosPitch = Math.cos(this._halfpitch);
  58483. this._sinYaw = Math.sin(this._halfyaw);
  58484. this._cosYaw = Math.cos(this._halfyaw);
  58485. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  58486. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  58487. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  58488. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  58489. };
  58490. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  58491. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  58492. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  58493. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  58494. this._rotMatrix.m[3] = 0;
  58495. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  58496. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  58497. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  58498. this._rotMatrix.m[7] = 0;
  58499. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  58500. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  58501. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  58502. this._rotMatrix.m[11] = 0;
  58503. this._rotMatrix.m[12] = 0;
  58504. this._rotMatrix.m[13] = 0;
  58505. this._rotMatrix.m[14] = 0;
  58506. this._rotMatrix.m[15] = 1.0;
  58507. };
  58508. /**
  58509. * Disposes the SPS.
  58510. */
  58511. SolidParticleSystem.prototype.dispose = function () {
  58512. this.mesh.dispose();
  58513. this.vars = null;
  58514. // drop references to internal big arrays for the GC
  58515. this._positions = null;
  58516. this._indices = null;
  58517. this._normals = null;
  58518. this._uvs = null;
  58519. this._colors = null;
  58520. this._indices32 = null;
  58521. this._positions32 = null;
  58522. this._normals32 = null;
  58523. this._fixedNormal32 = null;
  58524. this._uvs32 = null;
  58525. this._colors32 = null;
  58526. this.pickedParticles = null;
  58527. };
  58528. /**
  58529. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  58530. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58531. * @returns the SPS.
  58532. */
  58533. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  58534. if (!this._isVisibilityBoxLocked) {
  58535. this.mesh.refreshBoundingInfo();
  58536. }
  58537. return this;
  58538. };
  58539. /**
  58540. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  58541. * @param size the size (float) of the visibility box
  58542. * note : this doesn't lock the SPS mesh bounding box.
  58543. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58544. */
  58545. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  58546. var vis = size / 2;
  58547. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  58548. };
  58549. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  58550. /**
  58551. * Gets whether the SPS as always visible or not
  58552. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58553. */
  58554. get: function () {
  58555. return this._alwaysVisible;
  58556. },
  58557. /**
  58558. * Sets the SPS as always visible or not
  58559. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58560. */
  58561. set: function (val) {
  58562. this._alwaysVisible = val;
  58563. this.mesh.alwaysSelectAsActiveMesh = val;
  58564. },
  58565. enumerable: true,
  58566. configurable: true
  58567. });
  58568. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  58569. /**
  58570. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58571. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58572. */
  58573. get: function () {
  58574. return this._isVisibilityBoxLocked;
  58575. },
  58576. /**
  58577. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58578. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58579. */
  58580. set: function (val) {
  58581. this._isVisibilityBoxLocked = val;
  58582. var boundingInfo = this.mesh.getBoundingInfo();
  58583. boundingInfo.isLocked = val;
  58584. },
  58585. enumerable: true,
  58586. configurable: true
  58587. });
  58588. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  58589. /**
  58590. * Gets if `setParticles()` computes the particle rotations or not.
  58591. * Default value : true. The SPS is faster when it's set to false.
  58592. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58593. */
  58594. get: function () {
  58595. return this._computeParticleRotation;
  58596. },
  58597. /**
  58598. * Tells to `setParticles()` to compute the particle rotations or not.
  58599. * Default value : true. The SPS is faster when it's set to false.
  58600. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58601. */
  58602. set: function (val) {
  58603. this._computeParticleRotation = val;
  58604. },
  58605. enumerable: true,
  58606. configurable: true
  58607. });
  58608. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  58609. /**
  58610. * Gets if `setParticles()` computes the particle colors or not.
  58611. * Default value : true. The SPS is faster when it's set to false.
  58612. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58613. */
  58614. get: function () {
  58615. return this._computeParticleColor;
  58616. },
  58617. /**
  58618. * Tells to `setParticles()` to compute the particle colors or not.
  58619. * Default value : true. The SPS is faster when it's set to false.
  58620. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58621. */
  58622. set: function (val) {
  58623. this._computeParticleColor = val;
  58624. },
  58625. enumerable: true,
  58626. configurable: true
  58627. });
  58628. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  58629. /**
  58630. * Gets if `setParticles()` computes the particle textures or not.
  58631. * Default value : true. The SPS is faster when it's set to false.
  58632. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  58633. */
  58634. get: function () {
  58635. return this._computeParticleTexture;
  58636. },
  58637. set: function (val) {
  58638. this._computeParticleTexture = val;
  58639. },
  58640. enumerable: true,
  58641. configurable: true
  58642. });
  58643. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  58644. /**
  58645. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  58646. * Default value : false. The SPS is faster when it's set to false.
  58647. * Note : the particle custom vertex positions aren't stored values.
  58648. */
  58649. get: function () {
  58650. return this._computeParticleVertex;
  58651. },
  58652. /**
  58653. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  58654. * Default value : false. The SPS is faster when it's set to false.
  58655. * Note : the particle custom vertex positions aren't stored values.
  58656. */
  58657. set: function (val) {
  58658. this._computeParticleVertex = val;
  58659. },
  58660. enumerable: true,
  58661. configurable: true
  58662. });
  58663. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  58664. /**
  58665. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  58666. */
  58667. get: function () {
  58668. return this._computeBoundingBox;
  58669. },
  58670. /**
  58671. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  58672. */
  58673. set: function (val) {
  58674. this._computeBoundingBox = val;
  58675. },
  58676. enumerable: true,
  58677. configurable: true
  58678. });
  58679. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  58680. /**
  58681. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  58682. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  58683. * Default : `true`
  58684. */
  58685. get: function () {
  58686. return this._depthSortParticles;
  58687. },
  58688. /**
  58689. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  58690. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  58691. * Default : `true`
  58692. */
  58693. set: function (val) {
  58694. this._depthSortParticles = val;
  58695. },
  58696. enumerable: true,
  58697. configurable: true
  58698. });
  58699. // =======================================================================
  58700. // Particle behavior logic
  58701. // these following methods may be overwritten by the user to fit his needs
  58702. /**
  58703. * This function does nothing. It may be overwritten to set all the particle first values.
  58704. * The SPS doesn't call this function, you may have to call it by your own.
  58705. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58706. */
  58707. SolidParticleSystem.prototype.initParticles = function () {
  58708. };
  58709. /**
  58710. * This function does nothing. It may be overwritten to recycle a particle.
  58711. * The SPS doesn't call this function, you may have to call it by your own.
  58712. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58713. * @param particle The particle to recycle
  58714. * @returns the recycled particle
  58715. */
  58716. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  58717. return particle;
  58718. };
  58719. /**
  58720. * Updates a particle : this function should be overwritten by the user.
  58721. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  58722. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58723. * @example : just set a particle position or velocity and recycle conditions
  58724. * @param particle The particle to update
  58725. * @returns the updated particle
  58726. */
  58727. SolidParticleSystem.prototype.updateParticle = function (particle) {
  58728. return particle;
  58729. };
  58730. /**
  58731. * Updates a vertex of a particle : it can be overwritten by the user.
  58732. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  58733. * @param particle the current particle
  58734. * @param vertex the current index of the current particle
  58735. * @param pt the index of the current vertex in the particle shape
  58736. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  58737. * @example : just set a vertex particle position
  58738. * @returns the updated vertex
  58739. */
  58740. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  58741. return vertex;
  58742. };
  58743. /**
  58744. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  58745. * This does nothing and may be overwritten by the user.
  58746. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58747. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58748. * @param update the boolean update value actually passed to setParticles()
  58749. */
  58750. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  58751. };
  58752. /**
  58753. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  58754. * This will be passed three parameters.
  58755. * This does nothing and may be overwritten by the user.
  58756. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58757. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58758. * @param update the boolean update value actually passed to setParticles()
  58759. */
  58760. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  58761. };
  58762. return SolidParticleSystem;
  58763. }());
  58764. BABYLON.SolidParticleSystem = SolidParticleSystem;
  58765. })(BABYLON || (BABYLON = {}));
  58766. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  58767. var BABYLON;
  58768. (function (BABYLON) {
  58769. var ShaderMaterial = /** @class */ (function (_super) {
  58770. __extends(ShaderMaterial, _super);
  58771. function ShaderMaterial(name, scene, shaderPath, options) {
  58772. var _this = _super.call(this, name, scene) || this;
  58773. _this._textures = {};
  58774. _this._textureArrays = {};
  58775. _this._floats = {};
  58776. _this._ints = {};
  58777. _this._floatsArrays = {};
  58778. _this._colors3 = {};
  58779. _this._colors3Arrays = {};
  58780. _this._colors4 = {};
  58781. _this._vectors2 = {};
  58782. _this._vectors3 = {};
  58783. _this._vectors4 = {};
  58784. _this._matrices = {};
  58785. _this._matrices3x3 = {};
  58786. _this._matrices2x2 = {};
  58787. _this._vectors2Arrays = {};
  58788. _this._vectors3Arrays = {};
  58789. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  58790. _this._shaderPath = shaderPath;
  58791. options.needAlphaBlending = options.needAlphaBlending || false;
  58792. options.needAlphaTesting = options.needAlphaTesting || false;
  58793. options.attributes = options.attributes || ["position", "normal", "uv"];
  58794. options.uniforms = options.uniforms || ["worldViewProjection"];
  58795. options.uniformBuffers = options.uniformBuffers || [];
  58796. options.samplers = options.samplers || [];
  58797. options.defines = options.defines || [];
  58798. _this._options = options;
  58799. return _this;
  58800. }
  58801. ShaderMaterial.prototype.getClassName = function () {
  58802. return "ShaderMaterial";
  58803. };
  58804. ShaderMaterial.prototype.needAlphaBlending = function () {
  58805. return this._options.needAlphaBlending;
  58806. };
  58807. ShaderMaterial.prototype.needAlphaTesting = function () {
  58808. return this._options.needAlphaTesting;
  58809. };
  58810. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  58811. if (this._options.uniforms.indexOf(uniformName) === -1) {
  58812. this._options.uniforms.push(uniformName);
  58813. }
  58814. };
  58815. ShaderMaterial.prototype.setTexture = function (name, texture) {
  58816. if (this._options.samplers.indexOf(name) === -1) {
  58817. this._options.samplers.push(name);
  58818. }
  58819. this._textures[name] = texture;
  58820. return this;
  58821. };
  58822. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  58823. if (this._options.samplers.indexOf(name) === -1) {
  58824. this._options.samplers.push(name);
  58825. }
  58826. this._checkUniform(name);
  58827. this._textureArrays[name] = textures;
  58828. return this;
  58829. };
  58830. ShaderMaterial.prototype.setFloat = function (name, value) {
  58831. this._checkUniform(name);
  58832. this._floats[name] = value;
  58833. return this;
  58834. };
  58835. ShaderMaterial.prototype.setInt = function (name, value) {
  58836. this._checkUniform(name);
  58837. this._ints[name] = value;
  58838. return this;
  58839. };
  58840. ShaderMaterial.prototype.setFloats = function (name, value) {
  58841. this._checkUniform(name);
  58842. this._floatsArrays[name] = value;
  58843. return this;
  58844. };
  58845. ShaderMaterial.prototype.setColor3 = function (name, value) {
  58846. this._checkUniform(name);
  58847. this._colors3[name] = value;
  58848. return this;
  58849. };
  58850. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  58851. this._checkUniform(name);
  58852. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  58853. color.toArray(arr, arr.length);
  58854. return arr;
  58855. }, []);
  58856. return this;
  58857. };
  58858. ShaderMaterial.prototype.setColor4 = function (name, value) {
  58859. this._checkUniform(name);
  58860. this._colors4[name] = value;
  58861. return this;
  58862. };
  58863. ShaderMaterial.prototype.setVector2 = function (name, value) {
  58864. this._checkUniform(name);
  58865. this._vectors2[name] = value;
  58866. return this;
  58867. };
  58868. ShaderMaterial.prototype.setVector3 = function (name, value) {
  58869. this._checkUniform(name);
  58870. this._vectors3[name] = value;
  58871. return this;
  58872. };
  58873. ShaderMaterial.prototype.setVector4 = function (name, value) {
  58874. this._checkUniform(name);
  58875. this._vectors4[name] = value;
  58876. return this;
  58877. };
  58878. ShaderMaterial.prototype.setMatrix = function (name, value) {
  58879. this._checkUniform(name);
  58880. this._matrices[name] = value;
  58881. return this;
  58882. };
  58883. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  58884. this._checkUniform(name);
  58885. this._matrices3x3[name] = value;
  58886. return this;
  58887. };
  58888. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  58889. this._checkUniform(name);
  58890. this._matrices2x2[name] = value;
  58891. return this;
  58892. };
  58893. ShaderMaterial.prototype.setArray2 = function (name, value) {
  58894. this._checkUniform(name);
  58895. this._vectors2Arrays[name] = value;
  58896. return this;
  58897. };
  58898. ShaderMaterial.prototype.setArray3 = function (name, value) {
  58899. this._checkUniform(name);
  58900. this._vectors3Arrays[name] = value;
  58901. return this;
  58902. };
  58903. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  58904. if (!mesh) {
  58905. return true;
  58906. }
  58907. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  58908. return false;
  58909. }
  58910. return false;
  58911. };
  58912. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  58913. var scene = this.getScene();
  58914. var engine = scene.getEngine();
  58915. if (!this.checkReadyOnEveryCall) {
  58916. if (this._renderId === scene.getRenderId()) {
  58917. if (this._checkCache(scene, mesh, useInstances)) {
  58918. return true;
  58919. }
  58920. }
  58921. }
  58922. // Instances
  58923. var defines = [];
  58924. var attribs = [];
  58925. var fallbacks = new BABYLON.EffectFallbacks();
  58926. if (useInstances) {
  58927. defines.push("#define INSTANCES");
  58928. }
  58929. for (var index = 0; index < this._options.defines.length; index++) {
  58930. defines.push(this._options.defines[index]);
  58931. }
  58932. for (var index = 0; index < this._options.attributes.length; index++) {
  58933. attribs.push(this._options.attributes[index]);
  58934. }
  58935. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  58936. attribs.push(BABYLON.VertexBuffer.ColorKind);
  58937. defines.push("#define VERTEXCOLOR");
  58938. }
  58939. // Bones
  58940. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  58941. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58942. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58943. if (mesh.numBoneInfluencers > 4) {
  58944. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58945. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58946. }
  58947. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58948. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58949. fallbacks.addCPUSkinningFallback(0, mesh);
  58950. if (this._options.uniforms.indexOf("mBones") === -1) {
  58951. this._options.uniforms.push("mBones");
  58952. }
  58953. }
  58954. else {
  58955. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58956. }
  58957. // Textures
  58958. for (var name in this._textures) {
  58959. if (!this._textures[name].isReady()) {
  58960. return false;
  58961. }
  58962. }
  58963. // Alpha test
  58964. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  58965. defines.push("#define ALPHATEST");
  58966. }
  58967. var previousEffect = this._effect;
  58968. var join = defines.join("\n");
  58969. this._effect = engine.createEffect(this._shaderPath, {
  58970. attributes: attribs,
  58971. uniformsNames: this._options.uniforms,
  58972. uniformBuffersNames: this._options.uniformBuffers,
  58973. samplers: this._options.samplers,
  58974. defines: join,
  58975. fallbacks: fallbacks,
  58976. onCompiled: this.onCompiled,
  58977. onError: this.onError
  58978. }, engine);
  58979. if (!this._effect.isReady()) {
  58980. return false;
  58981. }
  58982. if (previousEffect !== this._effect) {
  58983. scene.resetCachedMaterial();
  58984. }
  58985. this._renderId = scene.getRenderId();
  58986. return true;
  58987. };
  58988. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  58989. var scene = this.getScene();
  58990. if (!this._effect) {
  58991. return;
  58992. }
  58993. if (this._options.uniforms.indexOf("world") !== -1) {
  58994. this._effect.setMatrix("world", world);
  58995. }
  58996. if (this._options.uniforms.indexOf("worldView") !== -1) {
  58997. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  58998. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  58999. }
  59000. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59001. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59002. }
  59003. };
  59004. ShaderMaterial.prototype.bind = function (world, mesh) {
  59005. // Std values
  59006. this.bindOnlyWorldMatrix(world);
  59007. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59008. if (this._options.uniforms.indexOf("view") !== -1) {
  59009. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59010. }
  59011. if (this._options.uniforms.indexOf("projection") !== -1) {
  59012. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59013. }
  59014. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59015. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59016. }
  59017. // Bones
  59018. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59019. var name;
  59020. // Texture
  59021. for (name in this._textures) {
  59022. this._effect.setTexture(name, this._textures[name]);
  59023. }
  59024. // Texture arrays
  59025. for (name in this._textureArrays) {
  59026. this._effect.setTextureArray(name, this._textureArrays[name]);
  59027. }
  59028. // Int
  59029. for (name in this._ints) {
  59030. this._effect.setInt(name, this._ints[name]);
  59031. }
  59032. // Float
  59033. for (name in this._floats) {
  59034. this._effect.setFloat(name, this._floats[name]);
  59035. }
  59036. // Floats
  59037. for (name in this._floatsArrays) {
  59038. this._effect.setArray(name, this._floatsArrays[name]);
  59039. }
  59040. // Color3
  59041. for (name in this._colors3) {
  59042. this._effect.setColor3(name, this._colors3[name]);
  59043. }
  59044. for (name in this._colors3Arrays) {
  59045. this._effect.setArray3(name, this._colors3Arrays[name]);
  59046. }
  59047. // Color4
  59048. for (name in this._colors4) {
  59049. var color = this._colors4[name];
  59050. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59051. }
  59052. // Vector2
  59053. for (name in this._vectors2) {
  59054. this._effect.setVector2(name, this._vectors2[name]);
  59055. }
  59056. // Vector3
  59057. for (name in this._vectors3) {
  59058. this._effect.setVector3(name, this._vectors3[name]);
  59059. }
  59060. // Vector4
  59061. for (name in this._vectors4) {
  59062. this._effect.setVector4(name, this._vectors4[name]);
  59063. }
  59064. // Matrix
  59065. for (name in this._matrices) {
  59066. this._effect.setMatrix(name, this._matrices[name]);
  59067. }
  59068. // Matrix 3x3
  59069. for (name in this._matrices3x3) {
  59070. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59071. }
  59072. // Matrix 2x2
  59073. for (name in this._matrices2x2) {
  59074. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59075. }
  59076. // Vector2Array
  59077. for (name in this._vectors2Arrays) {
  59078. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59079. }
  59080. // Vector3Array
  59081. for (name in this._vectors3Arrays) {
  59082. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59083. }
  59084. }
  59085. this._afterBind(mesh);
  59086. };
  59087. ShaderMaterial.prototype.getActiveTextures = function () {
  59088. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59089. for (var name in this._textures) {
  59090. activeTextures.push(this._textures[name]);
  59091. }
  59092. for (var name in this._textureArrays) {
  59093. var array = this._textureArrays[name];
  59094. for (var index = 0; index < array.length; index++) {
  59095. activeTextures.push(array[index]);
  59096. }
  59097. }
  59098. return activeTextures;
  59099. };
  59100. ShaderMaterial.prototype.hasTexture = function (texture) {
  59101. if (_super.prototype.hasTexture.call(this, texture)) {
  59102. return true;
  59103. }
  59104. for (var name in this._textures) {
  59105. if (this._textures[name] === texture) {
  59106. return true;
  59107. }
  59108. }
  59109. for (var name in this._textureArrays) {
  59110. var array = this._textureArrays[name];
  59111. for (var index = 0; index < array.length; index++) {
  59112. if (array[index] === texture) {
  59113. return true;
  59114. }
  59115. }
  59116. }
  59117. return false;
  59118. };
  59119. ShaderMaterial.prototype.clone = function (name) {
  59120. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59121. return newShaderMaterial;
  59122. };
  59123. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59124. if (forceDisposeTextures) {
  59125. var name;
  59126. for (name in this._textures) {
  59127. this._textures[name].dispose();
  59128. }
  59129. for (name in this._textureArrays) {
  59130. var array = this._textureArrays[name];
  59131. for (var index = 0; index < array.length; index++) {
  59132. array[index].dispose();
  59133. }
  59134. }
  59135. }
  59136. this._textures = {};
  59137. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59138. };
  59139. ShaderMaterial.prototype.serialize = function () {
  59140. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59141. serializationObject.customType = "BABYLON.ShaderMaterial";
  59142. serializationObject.options = this._options;
  59143. serializationObject.shaderPath = this._shaderPath;
  59144. var name;
  59145. // Texture
  59146. serializationObject.textures = {};
  59147. for (name in this._textures) {
  59148. serializationObject.textures[name] = this._textures[name].serialize();
  59149. }
  59150. // Texture arrays
  59151. serializationObject.textureArrays = {};
  59152. for (name in this._textureArrays) {
  59153. serializationObject.textureArrays[name] = [];
  59154. var array = this._textureArrays[name];
  59155. for (var index = 0; index < array.length; index++) {
  59156. serializationObject.textureArrays[name].push(array[index].serialize());
  59157. }
  59158. }
  59159. // Float
  59160. serializationObject.floats = {};
  59161. for (name in this._floats) {
  59162. serializationObject.floats[name] = this._floats[name];
  59163. }
  59164. // Float s
  59165. serializationObject.FloatArrays = {};
  59166. for (name in this._floatsArrays) {
  59167. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59168. }
  59169. // Color3
  59170. serializationObject.colors3 = {};
  59171. for (name in this._colors3) {
  59172. serializationObject.colors3[name] = this._colors3[name].asArray();
  59173. }
  59174. // Color3 array
  59175. serializationObject.colors3Arrays = {};
  59176. for (name in this._colors3Arrays) {
  59177. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59178. }
  59179. // Color4
  59180. serializationObject.colors4 = {};
  59181. for (name in this._colors4) {
  59182. serializationObject.colors4[name] = this._colors4[name].asArray();
  59183. }
  59184. // Vector2
  59185. serializationObject.vectors2 = {};
  59186. for (name in this._vectors2) {
  59187. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59188. }
  59189. // Vector3
  59190. serializationObject.vectors3 = {};
  59191. for (name in this._vectors3) {
  59192. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59193. }
  59194. // Vector4
  59195. serializationObject.vectors4 = {};
  59196. for (name in this._vectors4) {
  59197. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59198. }
  59199. // Matrix
  59200. serializationObject.matrices = {};
  59201. for (name in this._matrices) {
  59202. serializationObject.matrices[name] = this._matrices[name].asArray();
  59203. }
  59204. // Matrix 3x3
  59205. serializationObject.matrices3x3 = {};
  59206. for (name in this._matrices3x3) {
  59207. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59208. }
  59209. // Matrix 2x2
  59210. serializationObject.matrices2x2 = {};
  59211. for (name in this._matrices2x2) {
  59212. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59213. }
  59214. // Vector2Array
  59215. serializationObject.vectors2Arrays = {};
  59216. for (name in this._vectors2Arrays) {
  59217. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59218. }
  59219. // Vector3Array
  59220. serializationObject.vectors3Arrays = {};
  59221. for (name in this._vectors3Arrays) {
  59222. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59223. }
  59224. return serializationObject;
  59225. };
  59226. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59227. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59228. var name;
  59229. // Texture
  59230. for (name in source.textures) {
  59231. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59232. }
  59233. // Texture arrays
  59234. for (name in source.textureArrays) {
  59235. var array = source.textureArrays[name];
  59236. var textureArray = new Array();
  59237. for (var index = 0; index < array.length; index++) {
  59238. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59239. }
  59240. material.setTextureArray(name, textureArray);
  59241. }
  59242. // Float
  59243. for (name in source.floats) {
  59244. material.setFloat(name, source.floats[name]);
  59245. }
  59246. // Float s
  59247. for (name in source.floatsArrays) {
  59248. material.setFloats(name, source.floatsArrays[name]);
  59249. }
  59250. // Color3
  59251. for (name in source.colors3) {
  59252. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59253. }
  59254. // Color3 arrays
  59255. for (name in source.colors3Arrays) {
  59256. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59257. if (i % 3 === 0) {
  59258. arr.push([num]);
  59259. }
  59260. else {
  59261. arr[arr.length - 1].push(num);
  59262. }
  59263. return arr;
  59264. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59265. material.setColor3Array(name, colors);
  59266. }
  59267. // Color4
  59268. for (name in source.colors4) {
  59269. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59270. }
  59271. // Vector2
  59272. for (name in source.vectors2) {
  59273. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59274. }
  59275. // Vector3
  59276. for (name in source.vectors3) {
  59277. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59278. }
  59279. // Vector4
  59280. for (name in source.vectors4) {
  59281. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59282. }
  59283. // Matrix
  59284. for (name in source.matrices) {
  59285. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59286. }
  59287. // Matrix 3x3
  59288. for (name in source.matrices3x3) {
  59289. material.setMatrix3x3(name, source.matrices3x3[name]);
  59290. }
  59291. // Matrix 2x2
  59292. for (name in source.matrices2x2) {
  59293. material.setMatrix2x2(name, source.matrices2x2[name]);
  59294. }
  59295. // Vector2Array
  59296. for (name in source.vectors2Arrays) {
  59297. material.setArray2(name, source.vectors2Arrays[name]);
  59298. }
  59299. // Vector3Array
  59300. for (name in source.vectors3Arrays) {
  59301. material.setArray3(name, source.vectors3Arrays[name]);
  59302. }
  59303. return material;
  59304. };
  59305. return ShaderMaterial;
  59306. }(BABYLON.Material));
  59307. BABYLON.ShaderMaterial = ShaderMaterial;
  59308. })(BABYLON || (BABYLON = {}));
  59309. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59310. var BABYLON;
  59311. (function (BABYLON) {
  59312. var GroundMesh = /** @class */ (function (_super) {
  59313. __extends(GroundMesh, _super);
  59314. function GroundMesh(name, scene) {
  59315. var _this = _super.call(this, name, scene) || this;
  59316. _this.generateOctree = false;
  59317. return _this;
  59318. }
  59319. GroundMesh.prototype.getClassName = function () {
  59320. return "GroundMesh";
  59321. };
  59322. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59323. get: function () {
  59324. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59325. },
  59326. enumerable: true,
  59327. configurable: true
  59328. });
  59329. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59330. get: function () {
  59331. return this._subdivisionsX;
  59332. },
  59333. enumerable: true,
  59334. configurable: true
  59335. });
  59336. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59337. get: function () {
  59338. return this._subdivisionsY;
  59339. },
  59340. enumerable: true,
  59341. configurable: true
  59342. });
  59343. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59344. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59345. this._subdivisionsX = chunksCount;
  59346. this._subdivisionsY = chunksCount;
  59347. this.subdivide(chunksCount);
  59348. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59349. };
  59350. /**
  59351. * Returns a height (y) value in the Worl system :
  59352. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59353. * Returns the ground y position if (x, z) are outside the ground surface.
  59354. */
  59355. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59356. var world = this.getWorldMatrix();
  59357. var invMat = BABYLON.Tmp.Matrix[5];
  59358. world.invertToRef(invMat);
  59359. var tmpVect = BABYLON.Tmp.Vector3[8];
  59360. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59361. x = tmpVect.x;
  59362. z = tmpVect.z;
  59363. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59364. return this.position.y;
  59365. }
  59366. if (!this._heightQuads || this._heightQuads.length == 0) {
  59367. this._initHeightQuads();
  59368. this._computeHeightQuads();
  59369. }
  59370. var facet = this._getFacetAt(x, z);
  59371. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59372. // return y in the World system
  59373. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59374. return tmpVect.y;
  59375. };
  59376. /**
  59377. * Returns a normalized vector (Vector3) orthogonal to the ground
  59378. * at the ground coordinates (x, z) expressed in the World system.
  59379. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59380. */
  59381. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59382. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59383. this.getNormalAtCoordinatesToRef(x, z, normal);
  59384. return normal;
  59385. };
  59386. /**
  59387. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59388. * at the ground coordinates (x, z) expressed in the World system.
  59389. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59390. * Returns the GroundMesh.
  59391. */
  59392. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59393. var world = this.getWorldMatrix();
  59394. var tmpMat = BABYLON.Tmp.Matrix[5];
  59395. world.invertToRef(tmpMat);
  59396. var tmpVect = BABYLON.Tmp.Vector3[8];
  59397. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59398. x = tmpVect.x;
  59399. z = tmpVect.z;
  59400. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59401. return this;
  59402. }
  59403. if (!this._heightQuads || this._heightQuads.length == 0) {
  59404. this._initHeightQuads();
  59405. this._computeHeightQuads();
  59406. }
  59407. var facet = this._getFacetAt(x, z);
  59408. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59409. return this;
  59410. };
  59411. /**
  59412. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59413. * if the ground has been updated.
  59414. * This can be used in the render loop.
  59415. * Returns the GroundMesh.
  59416. */
  59417. GroundMesh.prototype.updateCoordinateHeights = function () {
  59418. if (!this._heightQuads || this._heightQuads.length == 0) {
  59419. this._initHeightQuads();
  59420. }
  59421. this._computeHeightQuads();
  59422. return this;
  59423. };
  59424. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59425. GroundMesh.prototype._getFacetAt = function (x, z) {
  59426. // retrieve col and row from x, z coordinates in the ground local system
  59427. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59428. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59429. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59430. var facet;
  59431. if (z < quad.slope.x * x + quad.slope.y) {
  59432. facet = quad.facet1;
  59433. }
  59434. else {
  59435. facet = quad.facet2;
  59436. }
  59437. return facet;
  59438. };
  59439. // Creates and populates the heightMap array with "facet" elements :
  59440. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59441. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59442. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59443. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59444. // Returns the GroundMesh.
  59445. GroundMesh.prototype._initHeightQuads = function () {
  59446. var subdivisionsX = this._subdivisionsX;
  59447. var subdivisionsY = this._subdivisionsY;
  59448. this._heightQuads = new Array();
  59449. for (var row = 0; row < subdivisionsY; row++) {
  59450. for (var col = 0; col < subdivisionsX; col++) {
  59451. 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) };
  59452. this._heightQuads[row * subdivisionsX + col] = quad;
  59453. }
  59454. }
  59455. return this;
  59456. };
  59457. // Compute each quad element values and update the the heightMap array :
  59458. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59459. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59460. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59461. // Returns the GroundMesh.
  59462. GroundMesh.prototype._computeHeightQuads = function () {
  59463. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59464. if (!positions) {
  59465. return this;
  59466. }
  59467. var v1 = BABYLON.Tmp.Vector3[3];
  59468. var v2 = BABYLON.Tmp.Vector3[2];
  59469. var v3 = BABYLON.Tmp.Vector3[1];
  59470. var v4 = BABYLON.Tmp.Vector3[0];
  59471. var v1v2 = BABYLON.Tmp.Vector3[4];
  59472. var v1v3 = BABYLON.Tmp.Vector3[5];
  59473. var v1v4 = BABYLON.Tmp.Vector3[6];
  59474. var norm1 = BABYLON.Tmp.Vector3[7];
  59475. var norm2 = BABYLON.Tmp.Vector3[8];
  59476. var i = 0;
  59477. var j = 0;
  59478. var k = 0;
  59479. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59480. var h = 0;
  59481. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59482. var d2 = 0;
  59483. var subdivisionsX = this._subdivisionsX;
  59484. var subdivisionsY = this._subdivisionsY;
  59485. for (var row = 0; row < subdivisionsY; row++) {
  59486. for (var col = 0; col < subdivisionsX; col++) {
  59487. i = col * 3;
  59488. j = row * (subdivisionsX + 1) * 3;
  59489. k = (row + 1) * (subdivisionsX + 1) * 3;
  59490. v1.x = positions[j + i];
  59491. v1.y = positions[j + i + 1];
  59492. v1.z = positions[j + i + 2];
  59493. v2.x = positions[j + i + 3];
  59494. v2.y = positions[j + i + 4];
  59495. v2.z = positions[j + i + 5];
  59496. v3.x = positions[k + i];
  59497. v3.y = positions[k + i + 1];
  59498. v3.z = positions[k + i + 2];
  59499. v4.x = positions[k + i + 3];
  59500. v4.y = positions[k + i + 4];
  59501. v4.z = positions[k + i + 5];
  59502. // 2D slope V1V4
  59503. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59504. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59505. // facet equations :
  59506. // we compute each facet normal vector
  59507. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59508. // we compute the value d by applying the equation to v1 which belongs to the plane
  59509. // then we store the facet equation in a Vector4
  59510. v2.subtractToRef(v1, v1v2);
  59511. v3.subtractToRef(v1, v1v3);
  59512. v4.subtractToRef(v1, v1v4);
  59513. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59514. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59515. norm1.normalize();
  59516. norm2.normalize();
  59517. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59518. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59519. var quad = this._heightQuads[row * subdivisionsX + col];
  59520. quad.slope.copyFromFloats(cd, h);
  59521. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59522. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59523. }
  59524. }
  59525. return this;
  59526. };
  59527. GroundMesh.prototype.serialize = function (serializationObject) {
  59528. _super.prototype.serialize.call(this, serializationObject);
  59529. serializationObject.subdivisionsX = this._subdivisionsX;
  59530. serializationObject.subdivisionsY = this._subdivisionsY;
  59531. serializationObject.minX = this._minX;
  59532. serializationObject.maxX = this._maxX;
  59533. serializationObject.minZ = this._minZ;
  59534. serializationObject.maxZ = this._maxZ;
  59535. serializationObject.width = this._width;
  59536. serializationObject.height = this._height;
  59537. };
  59538. GroundMesh.Parse = function (parsedMesh, scene) {
  59539. var result = new GroundMesh(parsedMesh.name, scene);
  59540. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59541. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59542. result._minX = parsedMesh.minX;
  59543. result._maxX = parsedMesh.maxX;
  59544. result._minZ = parsedMesh.minZ;
  59545. result._maxZ = parsedMesh.maxZ;
  59546. result._width = parsedMesh.width;
  59547. result._height = parsedMesh.height;
  59548. return result;
  59549. };
  59550. return GroundMesh;
  59551. }(BABYLON.Mesh));
  59552. BABYLON.GroundMesh = GroundMesh;
  59553. })(BABYLON || (BABYLON = {}));
  59554. //# sourceMappingURL=babylon.groundMesh.js.map
  59555. var BABYLON;
  59556. (function (BABYLON) {
  59557. /**
  59558. * Creates an instance based on a source mesh.
  59559. */
  59560. var InstancedMesh = /** @class */ (function (_super) {
  59561. __extends(InstancedMesh, _super);
  59562. function InstancedMesh(name, source) {
  59563. var _this = _super.call(this, name, source.getScene()) || this;
  59564. source.instances.push(_this);
  59565. _this._sourceMesh = source;
  59566. _this.position.copyFrom(source.position);
  59567. _this.rotation.copyFrom(source.rotation);
  59568. _this.scaling.copyFrom(source.scaling);
  59569. if (source.rotationQuaternion) {
  59570. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59571. }
  59572. _this.infiniteDistance = source.infiniteDistance;
  59573. _this.setPivotMatrix(source.getPivotMatrix());
  59574. _this.refreshBoundingInfo();
  59575. _this._syncSubMeshes();
  59576. return _this;
  59577. }
  59578. /**
  59579. * Returns the string "InstancedMesh".
  59580. */
  59581. InstancedMesh.prototype.getClassName = function () {
  59582. return "InstancedMesh";
  59583. };
  59584. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59585. // Methods
  59586. get: function () {
  59587. return this._sourceMesh.receiveShadows;
  59588. },
  59589. enumerable: true,
  59590. configurable: true
  59591. });
  59592. Object.defineProperty(InstancedMesh.prototype, "material", {
  59593. get: function () {
  59594. return this._sourceMesh.material;
  59595. },
  59596. enumerable: true,
  59597. configurable: true
  59598. });
  59599. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59600. get: function () {
  59601. return this._sourceMesh.visibility;
  59602. },
  59603. enumerable: true,
  59604. configurable: true
  59605. });
  59606. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  59607. get: function () {
  59608. return this._sourceMesh.skeleton;
  59609. },
  59610. enumerable: true,
  59611. configurable: true
  59612. });
  59613. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  59614. get: function () {
  59615. return this._sourceMesh.renderingGroupId;
  59616. },
  59617. set: function (value) {
  59618. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  59619. return;
  59620. }
  59621. //no-op with warning
  59622. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  59623. },
  59624. enumerable: true,
  59625. configurable: true
  59626. });
  59627. /**
  59628. * Returns the total number of vertices (integer).
  59629. */
  59630. InstancedMesh.prototype.getTotalVertices = function () {
  59631. return this._sourceMesh.getTotalVertices();
  59632. };
  59633. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  59634. get: function () {
  59635. return this._sourceMesh;
  59636. },
  59637. enumerable: true,
  59638. configurable: true
  59639. });
  59640. /**
  59641. * Is this node ready to be used/rendered
  59642. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  59643. * @return {boolean} is it ready
  59644. */
  59645. InstancedMesh.prototype.isReady = function (completeCheck) {
  59646. if (completeCheck === void 0) { completeCheck = false; }
  59647. return this._sourceMesh.isReady(completeCheck, true);
  59648. };
  59649. /**
  59650. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  59651. */
  59652. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  59653. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  59654. };
  59655. /**
  59656. * Sets the vertex data of the mesh geometry for the requested `kind`.
  59657. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  59658. * The `data` are either a numeric array either a Float32Array.
  59659. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  59660. * 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).
  59661. * Note that a new underlying VertexBuffer object is created each call.
  59662. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  59663. *
  59664. * Possible `kind` values :
  59665. * - BABYLON.VertexBuffer.PositionKind
  59666. * - BABYLON.VertexBuffer.UVKind
  59667. * - BABYLON.VertexBuffer.UV2Kind
  59668. * - BABYLON.VertexBuffer.UV3Kind
  59669. * - BABYLON.VertexBuffer.UV4Kind
  59670. * - BABYLON.VertexBuffer.UV5Kind
  59671. * - BABYLON.VertexBuffer.UV6Kind
  59672. * - BABYLON.VertexBuffer.ColorKind
  59673. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59674. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59675. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59676. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59677. *
  59678. * Returns the Mesh.
  59679. */
  59680. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  59681. if (this.sourceMesh) {
  59682. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  59683. }
  59684. return this.sourceMesh;
  59685. };
  59686. /**
  59687. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  59688. * If the mesh has no geometry, it is simply returned as it is.
  59689. * The `data` are either a numeric array either a Float32Array.
  59690. * No new underlying VertexBuffer object is created.
  59691. * 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.
  59692. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  59693. *
  59694. * Possible `kind` values :
  59695. * - BABYLON.VertexBuffer.PositionKind
  59696. * - BABYLON.VertexBuffer.UVKind
  59697. * - BABYLON.VertexBuffer.UV2Kind
  59698. * - BABYLON.VertexBuffer.UV3Kind
  59699. * - BABYLON.VertexBuffer.UV4Kind
  59700. * - BABYLON.VertexBuffer.UV5Kind
  59701. * - BABYLON.VertexBuffer.UV6Kind
  59702. * - BABYLON.VertexBuffer.ColorKind
  59703. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59704. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59705. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59706. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59707. *
  59708. * Returns the Mesh.
  59709. */
  59710. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  59711. if (this.sourceMesh) {
  59712. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  59713. }
  59714. return this.sourceMesh;
  59715. };
  59716. /**
  59717. * Sets the mesh indices.
  59718. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  59719. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  59720. * This method creates a new index buffer each call.
  59721. * Returns the Mesh.
  59722. */
  59723. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  59724. if (totalVertices === void 0) { totalVertices = null; }
  59725. if (this.sourceMesh) {
  59726. this.sourceMesh.setIndices(indices, totalVertices);
  59727. }
  59728. return this.sourceMesh;
  59729. };
  59730. /**
  59731. * Boolean : True if the mesh owns the requested kind of data.
  59732. */
  59733. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  59734. return this._sourceMesh.isVerticesDataPresent(kind);
  59735. };
  59736. /**
  59737. * Returns an array of indices (IndicesArray).
  59738. */
  59739. InstancedMesh.prototype.getIndices = function () {
  59740. return this._sourceMesh.getIndices();
  59741. };
  59742. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  59743. get: function () {
  59744. return this._sourceMesh._positions;
  59745. },
  59746. enumerable: true,
  59747. configurable: true
  59748. });
  59749. /**
  59750. * Sets a new updated BoundingInfo to the mesh.
  59751. * Returns the mesh.
  59752. */
  59753. InstancedMesh.prototype.refreshBoundingInfo = function () {
  59754. var meshBB = this._sourceMesh.getBoundingInfo();
  59755. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  59756. this._updateBoundingInfo();
  59757. return this;
  59758. };
  59759. InstancedMesh.prototype._preActivate = function () {
  59760. if (this._currentLOD) {
  59761. this._currentLOD._preActivate();
  59762. }
  59763. return this;
  59764. };
  59765. InstancedMesh.prototype._activate = function (renderId) {
  59766. if (this._currentLOD) {
  59767. this._currentLOD._registerInstanceForRenderId(this, renderId);
  59768. }
  59769. return this;
  59770. };
  59771. /**
  59772. * Returns the current associated LOD AbstractMesh.
  59773. */
  59774. InstancedMesh.prototype.getLOD = function (camera) {
  59775. if (!camera) {
  59776. return this;
  59777. }
  59778. var boundingInfo = this.getBoundingInfo();
  59779. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  59780. if (this._currentLOD === this.sourceMesh) {
  59781. return this;
  59782. }
  59783. return this._currentLOD;
  59784. };
  59785. InstancedMesh.prototype._syncSubMeshes = function () {
  59786. this.releaseSubMeshes();
  59787. if (this._sourceMesh.subMeshes) {
  59788. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  59789. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  59790. }
  59791. }
  59792. return this;
  59793. };
  59794. InstancedMesh.prototype._generatePointsArray = function () {
  59795. return this._sourceMesh._generatePointsArray();
  59796. };
  59797. /**
  59798. * Creates a new InstancedMesh from the current mesh.
  59799. * - name (string) : the cloned mesh name
  59800. * - newParent (optional Node) : the optional Node to parent the clone to.
  59801. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  59802. *
  59803. * Returns the clone.
  59804. */
  59805. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59806. var result = this._sourceMesh.createInstance(name);
  59807. // Deep copy
  59808. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  59809. // Bounding info
  59810. this.refreshBoundingInfo();
  59811. // Parent
  59812. if (newParent) {
  59813. result.parent = newParent;
  59814. }
  59815. if (!doNotCloneChildren) {
  59816. // Children
  59817. for (var index = 0; index < this.getScene().meshes.length; index++) {
  59818. var mesh = this.getScene().meshes[index];
  59819. if (mesh.parent === this) {
  59820. mesh.clone(mesh.name, result);
  59821. }
  59822. }
  59823. }
  59824. result.computeWorldMatrix(true);
  59825. return result;
  59826. };
  59827. /**
  59828. * Disposes the InstancedMesh.
  59829. * Returns nothing.
  59830. */
  59831. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  59832. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  59833. // Remove from mesh
  59834. var index = this._sourceMesh.instances.indexOf(this);
  59835. this._sourceMesh.instances.splice(index, 1);
  59836. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  59837. };
  59838. return InstancedMesh;
  59839. }(BABYLON.AbstractMesh));
  59840. BABYLON.InstancedMesh = InstancedMesh;
  59841. })(BABYLON || (BABYLON = {}));
  59842. //# sourceMappingURL=babylon.instancedMesh.js.map
  59843. var BABYLON;
  59844. (function (BABYLON) {
  59845. var LinesMesh = /** @class */ (function (_super) {
  59846. __extends(LinesMesh, _super);
  59847. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  59848. if (scene === void 0) { scene = null; }
  59849. if (parent === void 0) { parent = null; }
  59850. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  59851. _this.useVertexColor = useVertexColor;
  59852. _this.useVertexAlpha = useVertexAlpha;
  59853. _this.color = new BABYLON.Color3(1, 1, 1);
  59854. _this.alpha = 1;
  59855. if (source) {
  59856. _this.color = source.color.clone();
  59857. _this.alpha = source.alpha;
  59858. _this.useVertexColor = source.useVertexColor;
  59859. _this.useVertexAlpha = source.useVertexAlpha;
  59860. }
  59861. _this._intersectionThreshold = 0.1;
  59862. var defines = [];
  59863. var options = {
  59864. attributes: [BABYLON.VertexBuffer.PositionKind],
  59865. uniforms: ["world", "viewProjection"],
  59866. needAlphaBlending: true,
  59867. defines: defines
  59868. };
  59869. if (useVertexAlpha === false) {
  59870. options.needAlphaBlending = false;
  59871. }
  59872. if (!useVertexColor) {
  59873. options.uniforms.push("color");
  59874. }
  59875. else {
  59876. options.defines.push("#define VERTEXCOLOR");
  59877. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  59878. }
  59879. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  59880. return _this;
  59881. }
  59882. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  59883. /**
  59884. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59885. * This margin is expressed in world space coordinates, so its value may vary.
  59886. * Default value is 0.1
  59887. * @returns the intersection Threshold value.
  59888. */
  59889. get: function () {
  59890. return this._intersectionThreshold;
  59891. },
  59892. /**
  59893. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59894. * This margin is expressed in world space coordinates, so its value may vary.
  59895. * @param value the new threshold to apply
  59896. */
  59897. set: function (value) {
  59898. if (this._intersectionThreshold === value) {
  59899. return;
  59900. }
  59901. this._intersectionThreshold = value;
  59902. if (this.geometry) {
  59903. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  59904. }
  59905. },
  59906. enumerable: true,
  59907. configurable: true
  59908. });
  59909. /**
  59910. * Returns the string "LineMesh"
  59911. */
  59912. LinesMesh.prototype.getClassName = function () {
  59913. return "LinesMesh";
  59914. };
  59915. Object.defineProperty(LinesMesh.prototype, "material", {
  59916. get: function () {
  59917. return this._colorShader;
  59918. },
  59919. set: function (value) {
  59920. // Do nothing
  59921. },
  59922. enumerable: true,
  59923. configurable: true
  59924. });
  59925. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  59926. get: function () {
  59927. return false;
  59928. },
  59929. enumerable: true,
  59930. configurable: true
  59931. });
  59932. LinesMesh.prototype.createInstance = function (name) {
  59933. throw new Error("LinesMeshes do not support createInstance.");
  59934. };
  59935. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  59936. if (!this._geometry) {
  59937. return this;
  59938. }
  59939. // VBOs
  59940. this._geometry._bind(this._colorShader.getEffect());
  59941. // Color
  59942. if (!this.useVertexColor) {
  59943. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  59944. }
  59945. return this;
  59946. };
  59947. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  59948. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  59949. return this;
  59950. }
  59951. var engine = this.getScene().getEngine();
  59952. // Draw order
  59953. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  59954. return this;
  59955. };
  59956. LinesMesh.prototype.dispose = function (doNotRecurse) {
  59957. this._colorShader.dispose();
  59958. _super.prototype.dispose.call(this, doNotRecurse);
  59959. };
  59960. /**
  59961. * Returns a new LineMesh object cloned from the current one.
  59962. */
  59963. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59964. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  59965. };
  59966. return LinesMesh;
  59967. }(BABYLON.Mesh));
  59968. BABYLON.LinesMesh = LinesMesh;
  59969. })(BABYLON || (BABYLON = {}));
  59970. //# sourceMappingURL=babylon.linesMesh.js.map
  59971. var BABYLON;
  59972. (function (BABYLON) {
  59973. /**
  59974. * Class containing static functions to help procedurally build meshes
  59975. */
  59976. var MeshBuilder = /** @class */ (function () {
  59977. function MeshBuilder() {
  59978. }
  59979. MeshBuilder.updateSideOrientation = function (orientation) {
  59980. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  59981. return BABYLON.Mesh.DOUBLESIDE;
  59982. }
  59983. if (orientation === undefined || orientation === null) {
  59984. return BABYLON.Mesh.FRONTSIDE;
  59985. }
  59986. return orientation;
  59987. };
  59988. /**
  59989. * Creates a box mesh
  59990. * * The parameter `size` sets the size (float) of each box side (default 1)
  59991. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  59992. * * 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)
  59993. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  59994. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59995. * * 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
  59996. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59997. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  59998. * @param name defines the name of the mesh
  59999. * @param options defines the options used to create the mesh
  60000. * @param scene defines the hosting scene
  60001. * @returns the box mesh
  60002. */
  60003. MeshBuilder.CreateBox = function (name, options, scene) {
  60004. if (scene === void 0) { scene = null; }
  60005. var box = new BABYLON.Mesh(name, scene);
  60006. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60007. box._originalBuilderSideOrientation = options.sideOrientation;
  60008. var vertexData = BABYLON.VertexData.CreateBox(options);
  60009. vertexData.applyToMesh(box, options.updatable);
  60010. return box;
  60011. };
  60012. /**
  60013. * Creates a sphere mesh
  60014. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60015. * * 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`)
  60016. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60017. * * 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
  60018. * * 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)
  60019. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60020. * * 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
  60021. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60022. * @param name defines the name of the mesh
  60023. * @param options defines the options used to create the mesh
  60024. * @param scene defines the hosting scene
  60025. * @returns the sphere mesh
  60026. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60027. */
  60028. MeshBuilder.CreateSphere = function (name, options, scene) {
  60029. var sphere = new BABYLON.Mesh(name, scene);
  60030. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60031. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60032. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60033. vertexData.applyToMesh(sphere, options.updatable);
  60034. return sphere;
  60035. };
  60036. /**
  60037. * Creates a plane polygonal mesh. By default, this is a disc
  60038. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60039. * * 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
  60040. * * 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
  60041. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60042. * * 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
  60043. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60044. * @param name defines the name of the mesh
  60045. * @param options defines the options used to create the mesh
  60046. * @param scene defines the hosting scene
  60047. * @returns the plane polygonal mesh
  60048. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60049. */
  60050. MeshBuilder.CreateDisc = function (name, options, scene) {
  60051. if (scene === void 0) { scene = null; }
  60052. var disc = new BABYLON.Mesh(name, scene);
  60053. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60054. disc._originalBuilderSideOrientation = options.sideOrientation;
  60055. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60056. vertexData.applyToMesh(disc, options.updatable);
  60057. return disc;
  60058. };
  60059. /**
  60060. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60061. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60062. * * 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`)
  60063. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60064. * * 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
  60065. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60066. * * 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
  60067. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60068. * @param name defines the name of the mesh
  60069. * @param options defines the options used to create the mesh
  60070. * @param scene defines the hosting scene
  60071. * @returns the icosahedron mesh
  60072. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60073. */
  60074. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60075. var sphere = new BABYLON.Mesh(name, scene);
  60076. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60077. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60078. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60079. vertexData.applyToMesh(sphere, options.updatable);
  60080. return sphere;
  60081. };
  60082. ;
  60083. /**
  60084. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60085. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60086. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60087. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60088. * * 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
  60089. * * 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
  60090. * * 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
  60091. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60092. * * 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
  60093. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60094. * * 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
  60095. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60096. * * 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
  60097. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60098. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60099. * @param name defines the name of the mesh
  60100. * @param options defines the options used to create the mesh
  60101. * @param scene defines the hosting scene
  60102. * @returns the ribbon mesh
  60103. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60104. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60105. */
  60106. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60107. if (scene === void 0) { scene = null; }
  60108. var pathArray = options.pathArray;
  60109. var closeArray = options.closeArray;
  60110. var closePath = options.closePath;
  60111. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60112. var instance = options.instance;
  60113. var updatable = options.updatable;
  60114. if (instance) { // existing ribbon instance update
  60115. // positionFunction : ribbon case
  60116. // only pathArray and sideOrientation parameters are taken into account for positions update
  60117. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60118. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60119. var positionFunction = function (positions) {
  60120. var minlg = pathArray[0].length;
  60121. var i = 0;
  60122. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60123. for (var si = 1; si <= ns; si++) {
  60124. for (var p = 0; p < pathArray.length; p++) {
  60125. var path = pathArray[p];
  60126. var l = path.length;
  60127. minlg = (minlg < l) ? minlg : l;
  60128. var j = 0;
  60129. while (j < minlg) {
  60130. positions[i] = path[j].x;
  60131. positions[i + 1] = path[j].y;
  60132. positions[i + 2] = path[j].z;
  60133. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60134. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60135. }
  60136. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60137. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60138. }
  60139. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60140. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60141. }
  60142. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60143. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60144. }
  60145. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60146. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60147. }
  60148. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60149. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60150. }
  60151. j++;
  60152. i += 3;
  60153. }
  60154. if (instance._closePath) {
  60155. positions[i] = path[0].x;
  60156. positions[i + 1] = path[0].y;
  60157. positions[i + 2] = path[0].z;
  60158. i += 3;
  60159. }
  60160. }
  60161. }
  60162. };
  60163. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60164. positionFunction(positions);
  60165. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60166. instance._boundingInfo.update(instance._worldMatrix);
  60167. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60168. if (options.colors) {
  60169. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60170. for (var c = 0; c < options.colors.length; c++) {
  60171. colors[c * 4] = options.colors[c].r;
  60172. colors[c * 4 + 1] = options.colors[c].g;
  60173. colors[c * 4 + 2] = options.colors[c].b;
  60174. colors[c * 4 + 3] = options.colors[c].a;
  60175. }
  60176. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60177. }
  60178. if (options.uvs) {
  60179. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60180. for (var i = 0; i < options.uvs.length; i++) {
  60181. uvs[i * 2] = options.uvs[i].x;
  60182. uvs[i * 2 + 1] = options.uvs[i].y;
  60183. }
  60184. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60185. }
  60186. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60187. var indices = instance.getIndices();
  60188. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60189. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60190. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60191. if (instance._closePath) {
  60192. var indexFirst = 0;
  60193. var indexLast = 0;
  60194. for (var p = 0; p < pathArray.length; p++) {
  60195. indexFirst = instance._idx[p] * 3;
  60196. if (p + 1 < pathArray.length) {
  60197. indexLast = (instance._idx[p + 1] - 1) * 3;
  60198. }
  60199. else {
  60200. indexLast = normals.length - 3;
  60201. }
  60202. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60203. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60204. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60205. normals[indexLast] = normals[indexFirst];
  60206. normals[indexLast + 1] = normals[indexFirst + 1];
  60207. normals[indexLast + 2] = normals[indexFirst + 2];
  60208. }
  60209. }
  60210. if (!(instance.areNormalsFrozen)) {
  60211. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60212. }
  60213. }
  60214. return instance;
  60215. }
  60216. else { // new ribbon creation
  60217. var ribbon = new BABYLON.Mesh(name, scene);
  60218. ribbon._originalBuilderSideOrientation = sideOrientation;
  60219. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60220. if (closePath) {
  60221. ribbon._idx = vertexData._idx;
  60222. }
  60223. ribbon._closePath = closePath;
  60224. ribbon._closeArray = closeArray;
  60225. vertexData.applyToMesh(ribbon, updatable);
  60226. return ribbon;
  60227. }
  60228. };
  60229. /**
  60230. * Creates a cylinder or a cone mesh
  60231. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60232. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60233. * * 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.
  60234. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60235. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60236. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60237. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60238. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60239. * * 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).
  60240. * * 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
  60241. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60242. * * 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
  60243. * * 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.
  60244. * * If `enclose` is false, a ring surface is one element.
  60245. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60246. * * 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
  60247. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60248. * * 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
  60249. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60250. * @param name defines the name of the mesh
  60251. * @param options defines the options used to create the mesh
  60252. * @param scene defines the hosting scene
  60253. * @returns the cylinder mesh
  60254. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60255. */
  60256. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60257. var cylinder = new BABYLON.Mesh(name, scene);
  60258. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60259. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60260. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60261. vertexData.applyToMesh(cylinder, options.updatable);
  60262. return cylinder;
  60263. };
  60264. /**
  60265. * Creates a torus mesh
  60266. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60267. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60268. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60269. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60270. * * 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
  60271. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60272. * @param name defines the name of the mesh
  60273. * @param options defines the options used to create the mesh
  60274. * @param scene defines the hosting scene
  60275. * @returns the torus mesh
  60276. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60277. */
  60278. MeshBuilder.CreateTorus = function (name, options, scene) {
  60279. var torus = new BABYLON.Mesh(name, scene);
  60280. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60281. torus._originalBuilderSideOrientation = options.sideOrientation;
  60282. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60283. vertexData.applyToMesh(torus, options.updatable);
  60284. return torus;
  60285. };
  60286. /**
  60287. * Creates a torus knot mesh
  60288. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60289. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60290. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60291. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60292. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60293. * * 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
  60294. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60295. * @param name defines the name of the mesh
  60296. * @param options defines the options used to create the mesh
  60297. * @param scene defines the hosting scene
  60298. * @returns the torus knot mesh
  60299. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60300. */
  60301. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60302. var torusKnot = new BABYLON.Mesh(name, scene);
  60303. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60304. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60305. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60306. vertexData.applyToMesh(torusKnot, options.updatable);
  60307. return torusKnot;
  60308. };
  60309. /**
  60310. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60311. * * 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
  60312. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60313. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60314. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60315. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60316. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60317. * * 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
  60318. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60319. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60320. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  60321. * @param name defines the name of the new line system
  60322. * @param options defines the options used to create the line system
  60323. * @param scene defines the hosting scene
  60324. * @returns a new line system mesh
  60325. */
  60326. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60327. var instance = options.instance;
  60328. var lines = options.lines;
  60329. var colors = options.colors;
  60330. if (instance) { // lines update
  60331. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60332. var vertexColor;
  60333. var lineColors;
  60334. if (colors) {
  60335. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60336. }
  60337. var i = 0;
  60338. var c = 0;
  60339. for (var l = 0; l < lines.length; l++) {
  60340. var points = lines[l];
  60341. for (var p = 0; p < points.length; p++) {
  60342. positions[i] = points[p].x;
  60343. positions[i + 1] = points[p].y;
  60344. positions[i + 2] = points[p].z;
  60345. if (colors && vertexColor) {
  60346. lineColors = colors[l];
  60347. vertexColor[c] = lineColors[p].r;
  60348. vertexColor[c + 1] = lineColors[p].g;
  60349. vertexColor[c + 2] = lineColors[p].b;
  60350. vertexColor[c + 3] = lineColors[p].a;
  60351. c += 4;
  60352. }
  60353. i += 3;
  60354. }
  60355. }
  60356. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60357. if (colors && vertexColor) {
  60358. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60359. }
  60360. return instance;
  60361. }
  60362. // line system creation
  60363. var useVertexColor = (colors) ? true : false;
  60364. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60365. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60366. vertexData.applyToMesh(lineSystem, options.updatable);
  60367. return lineSystem;
  60368. };
  60369. /**
  60370. * Creates a line mesh
  60371. * 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
  60372. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60373. * * The parameter `points` is an array successive Vector3
  60374. * * 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
  60375. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60376. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60377. * * When updating an instance, remember that only point positions can change, not the number of points
  60378. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60379. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  60380. * @param name defines the name of the new line system
  60381. * @param options defines the options used to create the line system
  60382. * @param scene defines the hosting scene
  60383. * @returns a new line mesh
  60384. */
  60385. MeshBuilder.CreateLines = function (name, options, scene) {
  60386. if (scene === void 0) { scene = null; }
  60387. var colors = (options.colors) ? [options.colors] : null;
  60388. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60389. return lines;
  60390. };
  60391. /**
  60392. * Creates a dashed line mesh
  60393. * * 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
  60394. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60395. * * The parameter `points` is an array successive Vector3
  60396. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60397. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60398. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60399. * * 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
  60400. * * When updating an instance, remember that only point positions can change, not the number of points
  60401. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60402. * @param name defines the name of the mesh
  60403. * @param options defines the options used to create the mesh
  60404. * @param scene defines the hosting scene
  60405. * @returns the dashed line mesh
  60406. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  60407. */
  60408. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  60409. if (scene === void 0) { scene = null; }
  60410. var points = options.points;
  60411. var instance = options.instance;
  60412. var gapSize = options.gapSize || 1;
  60413. var dashSize = options.dashSize || 3;
  60414. if (instance) { // dashed lines update
  60415. var positionFunction = function (positions) {
  60416. var curvect = BABYLON.Vector3.Zero();
  60417. var nbSeg = positions.length / 6;
  60418. var lg = 0;
  60419. var nb = 0;
  60420. var shft = 0;
  60421. var dashshft = 0;
  60422. var curshft = 0;
  60423. var p = 0;
  60424. var i = 0;
  60425. var j = 0;
  60426. for (i = 0; i < points.length - 1; i++) {
  60427. points[i + 1].subtractToRef(points[i], curvect);
  60428. lg += curvect.length();
  60429. }
  60430. shft = lg / nbSeg;
  60431. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  60432. for (i = 0; i < points.length - 1; i++) {
  60433. points[i + 1].subtractToRef(points[i], curvect);
  60434. nb = Math.floor(curvect.length() / shft);
  60435. curvect.normalize();
  60436. j = 0;
  60437. while (j < nb && p < positions.length) {
  60438. curshft = shft * j;
  60439. positions[p] = points[i].x + curshft * curvect.x;
  60440. positions[p + 1] = points[i].y + curshft * curvect.y;
  60441. positions[p + 2] = points[i].z + curshft * curvect.z;
  60442. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  60443. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  60444. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  60445. p += 6;
  60446. j++;
  60447. }
  60448. }
  60449. while (p < positions.length) {
  60450. positions[p] = points[i].x;
  60451. positions[p + 1] = points[i].y;
  60452. positions[p + 2] = points[i].z;
  60453. p += 3;
  60454. }
  60455. };
  60456. instance.updateMeshPositions(positionFunction, false);
  60457. return instance;
  60458. }
  60459. // dashed lines creation
  60460. var dashedLines = new BABYLON.LinesMesh(name, scene);
  60461. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  60462. vertexData.applyToMesh(dashedLines, options.updatable);
  60463. dashedLines.dashSize = dashSize;
  60464. dashedLines.gapSize = gapSize;
  60465. return dashedLines;
  60466. };
  60467. /**
  60468. * 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.
  60469. * * 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.
  60470. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60471. * * 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.
  60472. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  60473. * * 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
  60474. * * 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
  60475. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  60476. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60477. * * 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
  60478. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  60479. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60480. * @param name defines the name of the mesh
  60481. * @param options defines the options used to create the mesh
  60482. * @param scene defines the hosting scene
  60483. * @returns the extruded shape mesh
  60484. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60485. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60486. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60487. */
  60488. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  60489. if (scene === void 0) { scene = null; }
  60490. var path = options.path;
  60491. var shape = options.shape;
  60492. var scale = options.scale || 1;
  60493. var rotation = options.rotation || 0;
  60494. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60495. var updatable = options.updatable;
  60496. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60497. var instance = options.instance || null;
  60498. var invertUV = options.invertUV || false;
  60499. 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);
  60500. };
  60501. /**
  60502. * Creates an custom extruded shape mesh.
  60503. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60504. * * 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.
  60505. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60506. * * 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
  60507. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  60508. * * 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
  60509. * * It must returns a float value that will be the scale value applied to the shape on each path point
  60510. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  60511. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  60512. * * 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
  60513. * * 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
  60514. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  60515. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60516. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60517. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60518. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60519. * @param name defines the name of the mesh
  60520. * @param options defines the options used to create the mesh
  60521. * @param scene defines the hosting scene
  60522. * @returns the custom extruded shape mesh
  60523. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  60524. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60525. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60526. */
  60527. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  60528. var path = options.path;
  60529. var shape = options.shape;
  60530. var scaleFunction = options.scaleFunction || (function () { return 1; });
  60531. var rotationFunction = options.rotationFunction || (function () { return 0; });
  60532. var ribbonCloseArray = options.ribbonCloseArray || false;
  60533. var ribbonClosePath = options.ribbonClosePath || false;
  60534. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60535. var updatable = options.updatable;
  60536. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60537. var instance = options.instance;
  60538. var invertUV = options.invertUV || false;
  60539. 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);
  60540. };
  60541. /**
  60542. * Creates lathe mesh.
  60543. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  60544. * * 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
  60545. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  60546. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  60547. * * 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
  60548. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  60549. * * 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
  60550. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60551. * * 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
  60552. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60553. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60554. * @param name defines the name of the mesh
  60555. * @param options defines the options used to create the mesh
  60556. * @param scene defines the hosting scene
  60557. * @returns the lathe mesh
  60558. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  60559. */
  60560. MeshBuilder.CreateLathe = function (name, options, scene) {
  60561. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  60562. var closed = (options.closed === undefined) ? true : options.closed;
  60563. var shape = options.shape;
  60564. var radius = options.radius || 1;
  60565. var tessellation = options.tessellation || 64;
  60566. var updatable = options.updatable;
  60567. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60568. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60569. var pi2 = Math.PI * 2;
  60570. var paths = new Array();
  60571. var invertUV = options.invertUV || false;
  60572. var i = 0;
  60573. var p = 0;
  60574. var step = pi2 / tessellation * arc;
  60575. var rotated;
  60576. var path = new Array();
  60577. for (i = 0; i <= tessellation; i++) {
  60578. var path = [];
  60579. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  60580. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  60581. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  60582. }
  60583. for (p = 0; p < shape.length; p++) {
  60584. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  60585. path.push(rotated);
  60586. }
  60587. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  60588. 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));
  60589. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  60590. }
  60591. paths.push(path);
  60592. }
  60593. // lathe ribbon
  60594. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60595. return lathe;
  60596. };
  60597. /**
  60598. * Creates a plane mesh
  60599. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  60600. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  60601. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  60602. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60603. * * 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
  60604. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60605. * @param name defines the name of the mesh
  60606. * @param options defines the options used to create the mesh
  60607. * @param scene defines the hosting scene
  60608. * @returns the plane mesh
  60609. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60610. */
  60611. MeshBuilder.CreatePlane = function (name, options, scene) {
  60612. var plane = new BABYLON.Mesh(name, scene);
  60613. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60614. plane._originalBuilderSideOrientation = options.sideOrientation;
  60615. var vertexData = BABYLON.VertexData.CreatePlane(options);
  60616. vertexData.applyToMesh(plane, options.updatable);
  60617. if (options.sourcePlane) {
  60618. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  60619. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  60620. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  60621. plane.rotate(vectorProduct, product);
  60622. }
  60623. return plane;
  60624. };
  60625. /**
  60626. * Creates a ground mesh
  60627. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  60628. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  60629. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60630. * @param name defines the name of the mesh
  60631. * @param options defines the options used to create the mesh
  60632. * @param scene defines the hosting scene
  60633. * @returns the ground mesh
  60634. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60635. */
  60636. MeshBuilder.CreateGround = function (name, options, scene) {
  60637. var ground = new BABYLON.GroundMesh(name, scene);
  60638. ground._setReady(false);
  60639. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  60640. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  60641. ground._width = options.width || 1;
  60642. ground._height = options.height || 1;
  60643. ground._maxX = ground._width / 2;
  60644. ground._maxZ = ground._height / 2;
  60645. ground._minX = -ground._maxX;
  60646. ground._minZ = -ground._maxZ;
  60647. var vertexData = BABYLON.VertexData.CreateGround(options);
  60648. vertexData.applyToMesh(ground, options.updatable);
  60649. ground._setReady(true);
  60650. return ground;
  60651. };
  60652. /**
  60653. * Creates a tiled ground mesh
  60654. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  60655. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  60656. * * 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
  60657. * * 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
  60658. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60659. * @param name defines the name of the mesh
  60660. * @param options defines the options used to create the mesh
  60661. * @param scene defines the hosting scene
  60662. * @returns the tiled ground mesh
  60663. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  60664. */
  60665. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  60666. var tiledGround = new BABYLON.Mesh(name, scene);
  60667. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  60668. vertexData.applyToMesh(tiledGround, options.updatable);
  60669. return tiledGround;
  60670. };
  60671. /**
  60672. * Creates a ground mesh from a height map
  60673. * * The parameter `url` sets the URL of the height map image resource.
  60674. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  60675. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  60676. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  60677. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  60678. * * 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.
  60679. * * 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).
  60680. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60681. * @param name defines the name of the mesh
  60682. * @param url defines the url to the height map
  60683. * @param options defines the options used to create the mesh
  60684. * @param scene defines the hosting scene
  60685. * @returns the ground mesh
  60686. * @see http://doc.babylonjs.com/babylon101/height_map
  60687. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  60688. */
  60689. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  60690. var width = options.width || 10.0;
  60691. var height = options.height || 10.0;
  60692. var subdivisions = options.subdivisions || 1 | 0;
  60693. var minHeight = options.minHeight || 0.0;
  60694. var maxHeight = options.maxHeight || 1.0;
  60695. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  60696. var updatable = options.updatable;
  60697. var onReady = options.onReady;
  60698. var ground = new BABYLON.GroundMesh(name, scene);
  60699. ground._subdivisionsX = subdivisions;
  60700. ground._subdivisionsY = subdivisions;
  60701. ground._width = width;
  60702. ground._height = height;
  60703. ground._maxX = ground._width / 2.0;
  60704. ground._maxZ = ground._height / 2.0;
  60705. ground._minX = -ground._maxX;
  60706. ground._minZ = -ground._maxZ;
  60707. ground._setReady(false);
  60708. var onload = function (img) {
  60709. // Getting height map data
  60710. var canvas = document.createElement("canvas");
  60711. var context = canvas.getContext("2d");
  60712. if (!context) {
  60713. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  60714. }
  60715. if (scene.isDisposed) {
  60716. return;
  60717. }
  60718. var bufferWidth = img.width;
  60719. var bufferHeight = img.height;
  60720. canvas.width = bufferWidth;
  60721. canvas.height = bufferHeight;
  60722. context.drawImage(img, 0, 0);
  60723. // Create VertexData from map data
  60724. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  60725. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  60726. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  60727. width: width, height: height,
  60728. subdivisions: subdivisions,
  60729. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  60730. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  60731. });
  60732. vertexData.applyToMesh(ground, updatable);
  60733. //execute ready callback, if set
  60734. if (onReady) {
  60735. onReady(ground);
  60736. }
  60737. ground._setReady(true);
  60738. };
  60739. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  60740. return ground;
  60741. };
  60742. /**
  60743. * Creates a polygon mesh
  60744. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  60745. * * 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
  60746. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60747. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60748. * * 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)
  60749. * * Remember you can only change the shape positions, not their number when updating a polygon
  60750. * @param name defines the name of the mesh
  60751. * @param options defines the options used to create the mesh
  60752. * @param scene defines the hosting scene
  60753. * @returns the polygon mesh
  60754. */
  60755. MeshBuilder.CreatePolygon = function (name, options, scene) {
  60756. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60757. var shape = options.shape;
  60758. var holes = options.holes || [];
  60759. var depth = options.depth || 0;
  60760. var contours = [];
  60761. var hole = [];
  60762. for (var i = 0; i < shape.length; i++) {
  60763. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  60764. }
  60765. var epsilon = 0.00000001;
  60766. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  60767. contours.pop();
  60768. }
  60769. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  60770. for (var hNb = 0; hNb < holes.length; hNb++) {
  60771. hole = [];
  60772. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  60773. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  60774. }
  60775. polygonTriangulation.addHole(hole);
  60776. }
  60777. var polygon = polygonTriangulation.build(options.updatable, depth);
  60778. polygon._originalBuilderSideOrientation = options.sideOrientation;
  60779. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  60780. vertexData.applyToMesh(polygon, options.updatable);
  60781. return polygon;
  60782. };
  60783. ;
  60784. /**
  60785. * Creates an extruded polygon mesh, with depth in the Y direction.
  60786. * * 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)
  60787. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60788. * @param name defines the name of the mesh
  60789. * @param options defines the options used to create the mesh
  60790. * @param scene defines the hosting scene
  60791. * @returns the polygon mesh
  60792. */
  60793. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  60794. return MeshBuilder.CreatePolygon(name, options, scene);
  60795. };
  60796. ;
  60797. /**
  60798. * Creates a tube mesh.
  60799. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60800. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  60801. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  60802. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  60803. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  60804. * * 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)
  60805. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  60806. * * 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
  60807. * * 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
  60808. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60809. * * 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
  60810. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60811. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60812. * @param name defines the name of the mesh
  60813. * @param options defines the options used to create the mesh
  60814. * @param scene defines the hosting scene
  60815. * @returns the tube mesh
  60816. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60817. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  60818. */
  60819. MeshBuilder.CreateTube = function (name, options, scene) {
  60820. var path = options.path;
  60821. var instance = options.instance;
  60822. var radius = 1.0;
  60823. if (instance) {
  60824. radius = instance.radius;
  60825. }
  60826. if (options.radius !== undefined) {
  60827. radius = options.radius;
  60828. }
  60829. ;
  60830. var tessellation = options.tessellation || 64 | 0;
  60831. var radiusFunction = options.radiusFunction || null;
  60832. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60833. var invertUV = options.invertUV || false;
  60834. var updatable = options.updatable;
  60835. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60836. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  60837. // tube geometry
  60838. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  60839. var tangents = path3D.getTangents();
  60840. var normals = path3D.getNormals();
  60841. var distances = path3D.getDistances();
  60842. var pi2 = Math.PI * 2;
  60843. var step = pi2 / tessellation * arc;
  60844. var returnRadius = function () { return radius; };
  60845. var radiusFunctionFinal = radiusFunction || returnRadius;
  60846. var circlePath;
  60847. var rad;
  60848. var normal;
  60849. var rotated;
  60850. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  60851. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  60852. for (var i = 0; i < path.length; i++) {
  60853. rad = radiusFunctionFinal(i, distances[i]); // current radius
  60854. circlePath = Array(); // current circle array
  60855. normal = normals[i]; // current normal
  60856. for (var t = 0; t < tessellation; t++) {
  60857. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  60858. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  60859. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  60860. rotated.scaleInPlace(rad).addInPlace(path[i]);
  60861. circlePath[t] = rotated;
  60862. }
  60863. circlePaths[index] = circlePath;
  60864. index++;
  60865. }
  60866. // cap
  60867. var capPath = function (nbPoints, pathIndex) {
  60868. var pointCap = Array();
  60869. for (var i = 0; i < nbPoints; i++) {
  60870. pointCap.push(path[pathIndex]);
  60871. }
  60872. return pointCap;
  60873. };
  60874. switch (cap) {
  60875. case BABYLON.Mesh.NO_CAP:
  60876. break;
  60877. case BABYLON.Mesh.CAP_START:
  60878. circlePaths[0] = capPath(tessellation, 0);
  60879. circlePaths[1] = circlePaths[2].slice(0);
  60880. break;
  60881. case BABYLON.Mesh.CAP_END:
  60882. circlePaths[index] = circlePaths[index - 1].slice(0);
  60883. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  60884. break;
  60885. case BABYLON.Mesh.CAP_ALL:
  60886. circlePaths[0] = capPath(tessellation, 0);
  60887. circlePaths[1] = circlePaths[2].slice(0);
  60888. circlePaths[index] = circlePaths[index - 1].slice(0);
  60889. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  60890. break;
  60891. default:
  60892. break;
  60893. }
  60894. return circlePaths;
  60895. };
  60896. var path3D;
  60897. var pathArray;
  60898. if (instance) { // tube update
  60899. var arc = options.arc || instance.arc;
  60900. path3D = (instance.path3D).update(path);
  60901. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  60902. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  60903. instance.path3D = path3D;
  60904. instance.pathArray = pathArray;
  60905. instance.arc = arc;
  60906. instance.radius = radius;
  60907. return instance;
  60908. }
  60909. // tube creation
  60910. path3D = new BABYLON.Path3D(path);
  60911. var newPathArray = new Array();
  60912. cap = (cap < 0 || cap > 3) ? 0 : cap;
  60913. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  60914. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60915. tube.pathArray = pathArray;
  60916. tube.path3D = path3D;
  60917. tube.tessellation = tessellation;
  60918. tube.cap = cap;
  60919. tube.arc = options.arc;
  60920. tube.radius = radius;
  60921. return tube;
  60922. };
  60923. /**
  60924. * Creates a polyhedron mesh
  60925. * * 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
  60926. * * The parameter `size` (positive float, default 1) sets the polygon size
  60927. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  60928. * * 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`
  60929. * * 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
  60930. * * 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)`)
  60931. * * 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
  60932. * * 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
  60933. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60934. * * 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
  60935. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60936. * @param name defines the name of the mesh
  60937. * @param options defines the options used to create the mesh
  60938. * @param scene defines the hosting scene
  60939. * @returns the polyhedron mesh
  60940. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  60941. */
  60942. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  60943. var polyhedron = new BABYLON.Mesh(name, scene);
  60944. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60945. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  60946. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  60947. vertexData.applyToMesh(polyhedron, options.updatable);
  60948. return polyhedron;
  60949. };
  60950. /**
  60951. * Creates a decal mesh.
  60952. * 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
  60953. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  60954. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  60955. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  60956. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  60957. * @param name defines the name of the mesh
  60958. * @param sourceMesh defines the mesh where the decal must be applied
  60959. * @param options defines the options used to create the mesh
  60960. * @param scene defines the hosting scene
  60961. * @returns the decal mesh
  60962. * @see http://doc.babylonjs.com/how_to/decals
  60963. */
  60964. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  60965. var indices = sourceMesh.getIndices();
  60966. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60967. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60968. var position = options.position || BABYLON.Vector3.Zero();
  60969. var normal = options.normal || BABYLON.Vector3.Up();
  60970. var size = options.size || BABYLON.Vector3.One();
  60971. var angle = options.angle || 0;
  60972. // Getting correct rotation
  60973. if (!normal) {
  60974. var target = new BABYLON.Vector3(0, 0, 1);
  60975. var camera = sourceMesh.getScene().activeCamera;
  60976. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  60977. normal = camera.globalPosition.subtract(cameraWorldTarget);
  60978. }
  60979. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  60980. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  60981. var pitch = Math.atan2(normal.y, len);
  60982. // Matrix
  60983. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  60984. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  60985. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  60986. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  60987. var vertexData = new BABYLON.VertexData();
  60988. vertexData.indices = [];
  60989. vertexData.positions = [];
  60990. vertexData.normals = [];
  60991. vertexData.uvs = [];
  60992. var currentVertexDataIndex = 0;
  60993. var extractDecalVector3 = function (indexId) {
  60994. var result = new BABYLON.PositionNormalVertex();
  60995. if (!indices || !positions || !normals) {
  60996. return result;
  60997. }
  60998. var vertexId = indices[indexId];
  60999. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61000. // Send vector to decal local world
  61001. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61002. // Get normal
  61003. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61004. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61005. return result;
  61006. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61007. var clip = function (vertices, axis) {
  61008. if (vertices.length === 0) {
  61009. return vertices;
  61010. }
  61011. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61012. var clipVertices = function (v0, v1) {
  61013. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61014. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61015. };
  61016. var result = new Array();
  61017. for (var index = 0; index < vertices.length; index += 3) {
  61018. var v1Out;
  61019. var v2Out;
  61020. var v3Out;
  61021. var total = 0;
  61022. var nV1 = null;
  61023. var nV2 = null;
  61024. var nV3 = null;
  61025. var nV4 = null;
  61026. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61027. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61028. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61029. v1Out = d1 > 0;
  61030. v2Out = d2 > 0;
  61031. v3Out = d3 > 0;
  61032. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61033. switch (total) {
  61034. case 0:
  61035. result.push(vertices[index]);
  61036. result.push(vertices[index + 1]);
  61037. result.push(vertices[index + 2]);
  61038. break;
  61039. case 1:
  61040. if (v1Out) {
  61041. nV1 = vertices[index + 1];
  61042. nV2 = vertices[index + 2];
  61043. nV3 = clipVertices(vertices[index], nV1);
  61044. nV4 = clipVertices(vertices[index], nV2);
  61045. }
  61046. if (v2Out) {
  61047. nV1 = vertices[index];
  61048. nV2 = vertices[index + 2];
  61049. nV3 = clipVertices(vertices[index + 1], nV1);
  61050. nV4 = clipVertices(vertices[index + 1], nV2);
  61051. result.push(nV3);
  61052. result.push(nV2.clone());
  61053. result.push(nV1.clone());
  61054. result.push(nV2.clone());
  61055. result.push(nV3.clone());
  61056. result.push(nV4);
  61057. break;
  61058. }
  61059. if (v3Out) {
  61060. nV1 = vertices[index];
  61061. nV2 = vertices[index + 1];
  61062. nV3 = clipVertices(vertices[index + 2], nV1);
  61063. nV4 = clipVertices(vertices[index + 2], nV2);
  61064. }
  61065. if (nV1 && nV2 && nV3 && nV4) {
  61066. result.push(nV1.clone());
  61067. result.push(nV2.clone());
  61068. result.push(nV3);
  61069. result.push(nV4);
  61070. result.push(nV3.clone());
  61071. result.push(nV2.clone());
  61072. }
  61073. break;
  61074. case 2:
  61075. if (!v1Out) {
  61076. nV1 = vertices[index].clone();
  61077. nV2 = clipVertices(nV1, vertices[index + 1]);
  61078. nV3 = clipVertices(nV1, vertices[index + 2]);
  61079. result.push(nV1);
  61080. result.push(nV2);
  61081. result.push(nV3);
  61082. }
  61083. if (!v2Out) {
  61084. nV1 = vertices[index + 1].clone();
  61085. nV2 = clipVertices(nV1, vertices[index + 2]);
  61086. nV3 = clipVertices(nV1, vertices[index]);
  61087. result.push(nV1);
  61088. result.push(nV2);
  61089. result.push(nV3);
  61090. }
  61091. if (!v3Out) {
  61092. nV1 = vertices[index + 2].clone();
  61093. nV2 = clipVertices(nV1, vertices[index]);
  61094. nV3 = clipVertices(nV1, vertices[index + 1]);
  61095. result.push(nV1);
  61096. result.push(nV2);
  61097. result.push(nV3);
  61098. }
  61099. break;
  61100. case 3:
  61101. break;
  61102. }
  61103. }
  61104. return result;
  61105. };
  61106. for (var index = 0; index < indices.length; index += 3) {
  61107. var faceVertices = new Array();
  61108. faceVertices.push(extractDecalVector3(index));
  61109. faceVertices.push(extractDecalVector3(index + 1));
  61110. faceVertices.push(extractDecalVector3(index + 2));
  61111. // Clip
  61112. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61113. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61114. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61115. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61116. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61117. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61118. if (faceVertices.length === 0) {
  61119. continue;
  61120. }
  61121. // Add UVs and get back to world
  61122. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61123. var vertex = faceVertices[vIndex];
  61124. //TODO check for Int32Array | Uint32Array | Uint16Array
  61125. vertexData.indices.push(currentVertexDataIndex);
  61126. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61127. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61128. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61129. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61130. currentVertexDataIndex++;
  61131. }
  61132. }
  61133. // Return mesh
  61134. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61135. vertexData.applyToMesh(decal);
  61136. decal.position = position.clone();
  61137. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61138. return decal;
  61139. };
  61140. // Privates
  61141. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61142. // extrusion geometry
  61143. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61144. var tangents = path3D.getTangents();
  61145. var normals = path3D.getNormals();
  61146. var binormals = path3D.getBinormals();
  61147. var distances = path3D.getDistances();
  61148. var angle = 0;
  61149. var returnScale = function () { return scale !== null ? scale : 1; };
  61150. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61151. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61152. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61153. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61154. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61155. for (var i = 0; i < curve.length; i++) {
  61156. var shapePath = new Array();
  61157. var angleStep = rotate(i, distances[i]);
  61158. var scaleRatio = scl(i, distances[i]);
  61159. for (var p = 0; p < shape.length; p++) {
  61160. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61161. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61162. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61163. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61164. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61165. shapePath[p] = rotated;
  61166. }
  61167. shapePaths[index] = shapePath;
  61168. angle += angleStep;
  61169. index++;
  61170. }
  61171. // cap
  61172. var capPath = function (shapePath) {
  61173. var pointCap = Array();
  61174. var barycenter = BABYLON.Vector3.Zero();
  61175. var i;
  61176. for (i = 0; i < shapePath.length; i++) {
  61177. barycenter.addInPlace(shapePath[i]);
  61178. }
  61179. barycenter.scaleInPlace(1.0 / shapePath.length);
  61180. for (i = 0; i < shapePath.length; i++) {
  61181. pointCap.push(barycenter);
  61182. }
  61183. return pointCap;
  61184. };
  61185. switch (cap) {
  61186. case BABYLON.Mesh.NO_CAP:
  61187. break;
  61188. case BABYLON.Mesh.CAP_START:
  61189. shapePaths[0] = capPath(shapePaths[2]);
  61190. shapePaths[1] = shapePaths[2];
  61191. break;
  61192. case BABYLON.Mesh.CAP_END:
  61193. shapePaths[index] = shapePaths[index - 1];
  61194. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61195. break;
  61196. case BABYLON.Mesh.CAP_ALL:
  61197. shapePaths[0] = capPath(shapePaths[2]);
  61198. shapePaths[1] = shapePaths[2];
  61199. shapePaths[index] = shapePaths[index - 1];
  61200. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61201. break;
  61202. default:
  61203. break;
  61204. }
  61205. return shapePaths;
  61206. };
  61207. var path3D;
  61208. var pathArray;
  61209. if (instance) { // instance update
  61210. path3D = (instance.path3D).update(curve);
  61211. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61212. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61213. return instance;
  61214. }
  61215. // extruded shape creation
  61216. path3D = new BABYLON.Path3D(curve);
  61217. var newShapePaths = new Array();
  61218. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61219. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61220. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61221. extrudedGeneric.pathArray = pathArray;
  61222. extrudedGeneric.path3D = path3D;
  61223. extrudedGeneric.cap = cap;
  61224. return extrudedGeneric;
  61225. };
  61226. return MeshBuilder;
  61227. }());
  61228. BABYLON.MeshBuilder = MeshBuilder;
  61229. })(BABYLON || (BABYLON = {}));
  61230. //# sourceMappingURL=babylon.meshBuilder.js.map
  61231. var BABYLON;
  61232. (function (BABYLON) {
  61233. /**
  61234. * Draco compression (https://google.github.io/draco/)
  61235. *
  61236. * This class wraps the Draco module.
  61237. *
  61238. * **Encoder**
  61239. *
  61240. * The encoder is not currently implemented.
  61241. *
  61242. * **Decoder**
  61243. *
  61244. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  61245. *
  61246. * To update the configuration, use the following code:
  61247. * ```javascript
  61248. * BABYLON.DracoCompression.Configuration = {
  61249. * decoder: {
  61250. * wasmUrl: "<url to the WebAssembly library>",
  61251. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  61252. * fallbackUrl: "<url to the fallback JavaScript library>",
  61253. * }
  61254. * };
  61255. * ```
  61256. *
  61257. * 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.
  61258. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  61259. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  61260. *
  61261. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  61262. * ```javascript
  61263. * var dracoCompression = new BABYLON.DracoCompression();
  61264. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  61265. * [BABYLON.VertexBuffer.PositionKind]: 0
  61266. * });
  61267. * ```
  61268. *
  61269. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  61270. */
  61271. var DracoCompression = /** @class */ (function () {
  61272. /**
  61273. * Constructor
  61274. */
  61275. function DracoCompression() {
  61276. }
  61277. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61278. /**
  61279. * Returns true if the decoder is available.
  61280. */
  61281. get: function () {
  61282. if (typeof DracoDecoderModule !== "undefined") {
  61283. return true;
  61284. }
  61285. var decoder = DracoCompression.Configuration.decoder;
  61286. if (decoder) {
  61287. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61288. return true;
  61289. }
  61290. if (decoder.fallbackUrl) {
  61291. return true;
  61292. }
  61293. }
  61294. return false;
  61295. },
  61296. enumerable: true,
  61297. configurable: true
  61298. });
  61299. /**
  61300. * Stop all async operations and release resources.
  61301. */
  61302. DracoCompression.prototype.dispose = function () {
  61303. };
  61304. /**
  61305. * Decode Draco compressed mesh data to vertex data.
  61306. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  61307. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61308. * @returns A promise that resolves with the decoded vertex data
  61309. */
  61310. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61311. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  61312. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61313. var module = wrappedModule.module;
  61314. var vertexData = new BABYLON.VertexData();
  61315. var buffer = new module.DecoderBuffer();
  61316. buffer.Init(dataView, dataView.byteLength);
  61317. var decoder = new module.Decoder();
  61318. var geometry;
  61319. var status;
  61320. try {
  61321. var type = decoder.GetEncodedGeometryType(buffer);
  61322. switch (type) {
  61323. case module.TRIANGULAR_MESH:
  61324. geometry = new module.Mesh();
  61325. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61326. break;
  61327. case module.POINT_CLOUD:
  61328. geometry = new module.PointCloud();
  61329. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61330. break;
  61331. default:
  61332. throw new Error("Invalid geometry type " + type);
  61333. }
  61334. if (!status.ok() || !geometry.ptr) {
  61335. throw new Error(status.error_msg());
  61336. }
  61337. var numPoints = geometry.num_points();
  61338. if (type === module.TRIANGULAR_MESH) {
  61339. var numFaces = geometry.num_faces();
  61340. var faceIndices = new module.DracoInt32Array();
  61341. try {
  61342. var indices = new Uint32Array(numFaces * 3);
  61343. for (var i = 0; i < numFaces; i++) {
  61344. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61345. var offset = i * 3;
  61346. indices[offset + 0] = faceIndices.GetValue(0);
  61347. indices[offset + 1] = faceIndices.GetValue(1);
  61348. indices[offset + 2] = faceIndices.GetValue(2);
  61349. }
  61350. vertexData.indices = indices;
  61351. }
  61352. finally {
  61353. module.destroy(faceIndices);
  61354. }
  61355. }
  61356. for (var kind in attributes) {
  61357. var uniqueId = attributes[kind];
  61358. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61359. var dracoData = new module.DracoFloat32Array();
  61360. try {
  61361. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61362. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61363. for (var i = 0; i < babylonData.length; i++) {
  61364. babylonData[i] = dracoData.GetValue(i);
  61365. }
  61366. vertexData.set(babylonData, kind);
  61367. }
  61368. finally {
  61369. module.destroy(dracoData);
  61370. }
  61371. }
  61372. }
  61373. finally {
  61374. if (geometry) {
  61375. module.destroy(geometry);
  61376. }
  61377. module.destroy(decoder);
  61378. module.destroy(buffer);
  61379. }
  61380. return vertexData;
  61381. });
  61382. };
  61383. DracoCompression._GetDecoderModule = function () {
  61384. if (!DracoCompression._DecoderModulePromise) {
  61385. var promise = null;
  61386. var config_1 = {};
  61387. if (typeof DracoDecoderModule !== "undefined") {
  61388. promise = Promise.resolve();
  61389. }
  61390. else {
  61391. var decoder = DracoCompression.Configuration.decoder;
  61392. if (decoder) {
  61393. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61394. promise = Promise.all([
  61395. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61396. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61397. config_1.wasmBinary = data;
  61398. })
  61399. ]);
  61400. }
  61401. else if (decoder.fallbackUrl) {
  61402. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61403. }
  61404. }
  61405. }
  61406. if (!promise) {
  61407. throw new Error("Draco decoder module is not available");
  61408. }
  61409. DracoCompression._DecoderModulePromise = promise.then(function () {
  61410. return new Promise(function (resolve) {
  61411. config_1.onModuleLoaded = function (decoderModule) {
  61412. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61413. resolve({ module: decoderModule });
  61414. };
  61415. DracoDecoderModule(config_1);
  61416. });
  61417. });
  61418. }
  61419. return DracoCompression._DecoderModulePromise;
  61420. };
  61421. DracoCompression._LoadScriptAsync = function (url) {
  61422. return new Promise(function (resolve, reject) {
  61423. BABYLON.Tools.LoadScript(url, function () {
  61424. resolve();
  61425. }, function (message) {
  61426. reject(new Error(message));
  61427. });
  61428. });
  61429. };
  61430. DracoCompression._LoadFileAsync = function (url) {
  61431. return new Promise(function (resolve, reject) {
  61432. BABYLON.Tools.LoadFile(url, function (data) {
  61433. resolve(data);
  61434. }, undefined, undefined, true, function (request, exception) {
  61435. reject(exception);
  61436. });
  61437. });
  61438. };
  61439. /**
  61440. * The configuration. Defaults to the following urls:
  61441. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  61442. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  61443. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61444. */
  61445. DracoCompression.Configuration = {
  61446. decoder: {
  61447. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  61448. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  61449. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61450. }
  61451. };
  61452. return DracoCompression;
  61453. }());
  61454. BABYLON.DracoCompression = DracoCompression;
  61455. })(BABYLON || (BABYLON = {}));
  61456. //# sourceMappingURL=babylon.dracoCompression.js.map
  61457. var BABYLON;
  61458. (function (BABYLON) {
  61459. var AudioEngine = /** @class */ (function () {
  61460. function AudioEngine() {
  61461. this._audioContext = null;
  61462. this._audioContextInitialized = false;
  61463. this.canUseWebAudio = false;
  61464. this.WarnedWebAudioUnsupported = false;
  61465. this.unlocked = false;
  61466. this.isMP3supported = false;
  61467. this.isOGGsupported = false;
  61468. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  61469. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  61470. this.canUseWebAudio = true;
  61471. }
  61472. var audioElem = document.createElement('audio');
  61473. try {
  61474. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  61475. this.isMP3supported = true;
  61476. }
  61477. }
  61478. catch (e) {
  61479. // protect error during capability check.
  61480. }
  61481. try {
  61482. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  61483. this.isOGGsupported = true;
  61484. }
  61485. }
  61486. catch (e) {
  61487. // protect error during capability check.
  61488. }
  61489. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  61490. this._unlockiOSaudio();
  61491. }
  61492. else {
  61493. this.unlocked = true;
  61494. }
  61495. }
  61496. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  61497. get: function () {
  61498. if (!this._audioContextInitialized) {
  61499. this._initializeAudioContext();
  61500. }
  61501. return this._audioContext;
  61502. },
  61503. enumerable: true,
  61504. configurable: true
  61505. });
  61506. AudioEngine.prototype._unlockiOSaudio = function () {
  61507. var _this = this;
  61508. var unlockaudio = function () {
  61509. if (!_this.audioContext) {
  61510. return;
  61511. }
  61512. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  61513. var source = _this.audioContext.createBufferSource();
  61514. source.buffer = buffer;
  61515. source.connect(_this.audioContext.destination);
  61516. source.start(0);
  61517. setTimeout(function () {
  61518. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  61519. _this.unlocked = true;
  61520. window.removeEventListener('touchend', unlockaudio, false);
  61521. if (_this.onAudioUnlocked) {
  61522. _this.onAudioUnlocked();
  61523. }
  61524. }
  61525. }, 0);
  61526. };
  61527. window.addEventListener('touchend', unlockaudio, false);
  61528. };
  61529. AudioEngine.prototype._initializeAudioContext = function () {
  61530. try {
  61531. if (this.canUseWebAudio) {
  61532. this._audioContext = new AudioContext();
  61533. // create a global volume gain node
  61534. this.masterGain = this._audioContext.createGain();
  61535. this.masterGain.gain.value = 1;
  61536. this.masterGain.connect(this._audioContext.destination);
  61537. this._audioContextInitialized = true;
  61538. }
  61539. }
  61540. catch (e) {
  61541. this.canUseWebAudio = false;
  61542. BABYLON.Tools.Error("Web Audio: " + e.message);
  61543. }
  61544. };
  61545. AudioEngine.prototype.dispose = function () {
  61546. if (this.canUseWebAudio && this._audioContextInitialized) {
  61547. if (this._connectedAnalyser && this._audioContext) {
  61548. this._connectedAnalyser.stopDebugCanvas();
  61549. this._connectedAnalyser.dispose();
  61550. this.masterGain.disconnect();
  61551. this.masterGain.connect(this._audioContext.destination);
  61552. this._connectedAnalyser = null;
  61553. }
  61554. this.masterGain.gain.value = 1;
  61555. }
  61556. this.WarnedWebAudioUnsupported = false;
  61557. };
  61558. AudioEngine.prototype.getGlobalVolume = function () {
  61559. if (this.canUseWebAudio && this._audioContextInitialized) {
  61560. return this.masterGain.gain.value;
  61561. }
  61562. else {
  61563. return -1;
  61564. }
  61565. };
  61566. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  61567. if (this.canUseWebAudio && this._audioContextInitialized) {
  61568. this.masterGain.gain.value = newVolume;
  61569. }
  61570. };
  61571. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  61572. if (this._connectedAnalyser) {
  61573. this._connectedAnalyser.stopDebugCanvas();
  61574. }
  61575. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  61576. this._connectedAnalyser = analyser;
  61577. this.masterGain.disconnect();
  61578. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  61579. }
  61580. };
  61581. return AudioEngine;
  61582. }());
  61583. BABYLON.AudioEngine = AudioEngine;
  61584. })(BABYLON || (BABYLON = {}));
  61585. //# sourceMappingURL=babylon.audioEngine.js.map
  61586. var BABYLON;
  61587. (function (BABYLON) {
  61588. var Sound = /** @class */ (function () {
  61589. /**
  61590. * Create a sound and attach it to a scene
  61591. * @param name Name of your sound
  61592. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  61593. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  61594. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  61595. */
  61596. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  61597. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  61598. var _this = this;
  61599. this.autoplay = false;
  61600. this.loop = false;
  61601. this.useCustomAttenuation = false;
  61602. this.spatialSound = false;
  61603. this.refDistance = 1;
  61604. this.rolloffFactor = 1;
  61605. this.maxDistance = 100;
  61606. this.distanceModel = "linear";
  61607. this._panningModel = "equalpower";
  61608. this._playbackRate = 1;
  61609. this._streaming = false;
  61610. this._startTime = 0;
  61611. this._startOffset = 0;
  61612. this._position = BABYLON.Vector3.Zero();
  61613. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  61614. this._volume = 1;
  61615. this._isReadyToPlay = false;
  61616. this.isPlaying = false;
  61617. this.isPaused = false;
  61618. this._isDirectional = false;
  61619. // Used if you'd like to create a directional sound.
  61620. // If not set, the sound will be omnidirectional
  61621. this._coneInnerAngle = 360;
  61622. this._coneOuterAngle = 360;
  61623. this._coneOuterGain = 0;
  61624. this._isOutputConnected = false;
  61625. this._urlType = "Unknown";
  61626. this.name = name;
  61627. this._scene = scene;
  61628. this._readyToPlayCallback = readyToPlayCallback;
  61629. // Default custom attenuation function is a linear attenuation
  61630. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  61631. if (currentDistance < maxDistance) {
  61632. return currentVolume * (1 - currentDistance / maxDistance);
  61633. }
  61634. else {
  61635. return 0;
  61636. }
  61637. };
  61638. if (options) {
  61639. this.autoplay = options.autoplay || false;
  61640. this.loop = options.loop || false;
  61641. // if volume === 0, we need another way to check this option
  61642. if (options.volume !== undefined) {
  61643. this._volume = options.volume;
  61644. }
  61645. this.spatialSound = options.spatialSound || false;
  61646. this.maxDistance = options.maxDistance || 100;
  61647. this.useCustomAttenuation = options.useCustomAttenuation || false;
  61648. this.rolloffFactor = options.rolloffFactor || 1;
  61649. this.refDistance = options.refDistance || 1;
  61650. this.distanceModel = options.distanceModel || "linear";
  61651. this._playbackRate = options.playbackRate || 1;
  61652. this._streaming = options.streaming || false;
  61653. }
  61654. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61655. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  61656. this._soundGain.gain.value = this._volume;
  61657. this._inputAudioNode = this._soundGain;
  61658. this._ouputAudioNode = this._soundGain;
  61659. if (this.spatialSound) {
  61660. this._createSpatialParameters();
  61661. }
  61662. this._scene.mainSoundTrack.AddSound(this);
  61663. var validParameter = true;
  61664. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  61665. if (urlOrArrayBuffer) {
  61666. try {
  61667. if (typeof (urlOrArrayBuffer) === "string") {
  61668. this._urlType = "String";
  61669. }
  61670. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  61671. this._urlType = "ArrayBuffer";
  61672. }
  61673. else if (urlOrArrayBuffer instanceof MediaStream) {
  61674. this._urlType = "MediaStream";
  61675. }
  61676. else if (Array.isArray(urlOrArrayBuffer)) {
  61677. this._urlType = "Array";
  61678. }
  61679. var urls = [];
  61680. var codecSupportedFound = false;
  61681. switch (this._urlType) {
  61682. case "MediaStream":
  61683. this._streaming = true;
  61684. this._isReadyToPlay = true;
  61685. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);
  61686. if (this.autoplay) {
  61687. this.play();
  61688. }
  61689. if (this._readyToPlayCallback) {
  61690. this._readyToPlayCallback();
  61691. }
  61692. break;
  61693. case "ArrayBuffer":
  61694. if (urlOrArrayBuffer.byteLength > 0) {
  61695. codecSupportedFound = true;
  61696. this._soundLoaded(urlOrArrayBuffer);
  61697. }
  61698. break;
  61699. case "String":
  61700. urls.push(urlOrArrayBuffer);
  61701. case "Array":
  61702. if (urls.length === 0)
  61703. urls = urlOrArrayBuffer;
  61704. // If we found a supported format, we load it immediately and stop the loop
  61705. for (var i = 0; i < urls.length; i++) {
  61706. var url = urls[i];
  61707. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  61708. codecSupportedFound = true;
  61709. }
  61710. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  61711. codecSupportedFound = true;
  61712. }
  61713. if (url.indexOf(".wav", url.length - 4) !== -1) {
  61714. codecSupportedFound = true;
  61715. }
  61716. if (url.indexOf("blob:") !== -1) {
  61717. codecSupportedFound = true;
  61718. }
  61719. if (codecSupportedFound) {
  61720. // Loading sound using XHR2
  61721. if (!this._streaming) {
  61722. this._scene._loadFile(url, function (data) {
  61723. _this._soundLoaded(data);
  61724. }, undefined, true, true, function (exception) {
  61725. if (exception) {
  61726. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  61727. }
  61728. BABYLON.Tools.Error("Sound creation aborted.");
  61729. _this._scene.mainSoundTrack.RemoveSound(_this);
  61730. });
  61731. }
  61732. // Streaming sound using HTML5 Audio tag
  61733. else {
  61734. this._htmlAudioElement = new Audio(url);
  61735. this._htmlAudioElement.controls = false;
  61736. this._htmlAudioElement.loop = this.loop;
  61737. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  61738. this._htmlAudioElement.preload = "auto";
  61739. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  61740. _this._isReadyToPlay = true;
  61741. if (_this.autoplay) {
  61742. _this.play();
  61743. }
  61744. if (_this._readyToPlayCallback) {
  61745. _this._readyToPlayCallback();
  61746. }
  61747. });
  61748. document.body.appendChild(this._htmlAudioElement);
  61749. }
  61750. break;
  61751. }
  61752. }
  61753. break;
  61754. default:
  61755. validParameter = false;
  61756. break;
  61757. }
  61758. if (!validParameter) {
  61759. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  61760. }
  61761. else {
  61762. if (!codecSupportedFound) {
  61763. this._isReadyToPlay = true;
  61764. // Simulating a ready to play event to avoid breaking code path
  61765. if (this._readyToPlayCallback) {
  61766. window.setTimeout(function () {
  61767. if (_this._readyToPlayCallback) {
  61768. _this._readyToPlayCallback();
  61769. }
  61770. }, 1000);
  61771. }
  61772. }
  61773. }
  61774. }
  61775. catch (ex) {
  61776. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  61777. this._scene.mainSoundTrack.RemoveSound(this);
  61778. }
  61779. }
  61780. }
  61781. else {
  61782. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  61783. this._scene.mainSoundTrack.AddSound(this);
  61784. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  61785. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  61786. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  61787. }
  61788. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  61789. if (this._readyToPlayCallback) {
  61790. window.setTimeout(function () {
  61791. if (_this._readyToPlayCallback) {
  61792. _this._readyToPlayCallback();
  61793. }
  61794. }, 1000);
  61795. }
  61796. }
  61797. }
  61798. Sound.prototype.dispose = function () {
  61799. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61800. if (this.isPlaying) {
  61801. this.stop();
  61802. }
  61803. this._isReadyToPlay = false;
  61804. if (this.soundTrackId === -1) {
  61805. this._scene.mainSoundTrack.RemoveSound(this);
  61806. }
  61807. else {
  61808. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  61809. }
  61810. if (this._soundGain) {
  61811. this._soundGain.disconnect();
  61812. this._soundGain = null;
  61813. }
  61814. if (this._soundPanner) {
  61815. this._soundPanner.disconnect();
  61816. this._soundPanner = null;
  61817. }
  61818. if (this._soundSource) {
  61819. this._soundSource.disconnect();
  61820. this._soundSource = null;
  61821. }
  61822. this._audioBuffer = null;
  61823. if (this._htmlAudioElement) {
  61824. this._htmlAudioElement.pause();
  61825. this._htmlAudioElement.src = "";
  61826. document.body.removeChild(this._htmlAudioElement);
  61827. }
  61828. if (this._streamingSource) {
  61829. this._streamingSource.disconnect();
  61830. }
  61831. if (this._connectedMesh && this._registerFunc) {
  61832. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61833. this._connectedMesh = null;
  61834. }
  61835. }
  61836. };
  61837. Sound.prototype.isReady = function () {
  61838. return this._isReadyToPlay;
  61839. };
  61840. Sound.prototype._soundLoaded = function (audioData) {
  61841. var _this = this;
  61842. if (!BABYLON.Engine.audioEngine.audioContext) {
  61843. return;
  61844. }
  61845. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  61846. _this._audioBuffer = buffer;
  61847. _this._isReadyToPlay = true;
  61848. if (_this.autoplay) {
  61849. _this.play();
  61850. }
  61851. if (_this._readyToPlayCallback) {
  61852. _this._readyToPlayCallback();
  61853. }
  61854. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  61855. };
  61856. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  61857. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61858. this._audioBuffer = audioBuffer;
  61859. this._isReadyToPlay = true;
  61860. }
  61861. };
  61862. Sound.prototype.updateOptions = function (options) {
  61863. if (options) {
  61864. this.loop = options.loop || this.loop;
  61865. this.maxDistance = options.maxDistance || this.maxDistance;
  61866. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  61867. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  61868. this.refDistance = options.refDistance || this.refDistance;
  61869. this.distanceModel = options.distanceModel || this.distanceModel;
  61870. this._playbackRate = options.playbackRate || this._playbackRate;
  61871. this._updateSpatialParameters();
  61872. if (this.isPlaying) {
  61873. if (this._streaming && this._htmlAudioElement) {
  61874. this._htmlAudioElement.playbackRate = this._playbackRate;
  61875. }
  61876. else {
  61877. if (this._soundSource) {
  61878. this._soundSource.playbackRate.value = this._playbackRate;
  61879. }
  61880. }
  61881. }
  61882. }
  61883. };
  61884. Sound.prototype._createSpatialParameters = function () {
  61885. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61886. if (this._scene.headphone) {
  61887. this._panningModel = "HRTF";
  61888. }
  61889. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  61890. this._updateSpatialParameters();
  61891. this._soundPanner.connect(this._ouputAudioNode);
  61892. this._inputAudioNode = this._soundPanner;
  61893. }
  61894. };
  61895. Sound.prototype._updateSpatialParameters = function () {
  61896. if (this.spatialSound && this._soundPanner) {
  61897. if (this.useCustomAttenuation) {
  61898. // Tricks to disable in a way embedded Web Audio attenuation
  61899. this._soundPanner.distanceModel = "linear";
  61900. this._soundPanner.maxDistance = Number.MAX_VALUE;
  61901. this._soundPanner.refDistance = 1;
  61902. this._soundPanner.rolloffFactor = 1;
  61903. this._soundPanner.panningModel = this._panningModel;
  61904. }
  61905. else {
  61906. this._soundPanner.distanceModel = this.distanceModel;
  61907. this._soundPanner.maxDistance = this.maxDistance;
  61908. this._soundPanner.refDistance = this.refDistance;
  61909. this._soundPanner.rolloffFactor = this.rolloffFactor;
  61910. this._soundPanner.panningModel = this._panningModel;
  61911. }
  61912. }
  61913. };
  61914. Sound.prototype.switchPanningModelToHRTF = function () {
  61915. this._panningModel = "HRTF";
  61916. this._switchPanningModel();
  61917. };
  61918. Sound.prototype.switchPanningModelToEqualPower = function () {
  61919. this._panningModel = "equalpower";
  61920. this._switchPanningModel();
  61921. };
  61922. Sound.prototype._switchPanningModel = function () {
  61923. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  61924. this._soundPanner.panningModel = this._panningModel;
  61925. }
  61926. };
  61927. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  61928. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61929. if (this._isOutputConnected) {
  61930. this._ouputAudioNode.disconnect();
  61931. }
  61932. this._ouputAudioNode.connect(soundTrackAudioNode);
  61933. this._isOutputConnected = true;
  61934. }
  61935. };
  61936. /**
  61937. * Transform this sound into a directional source
  61938. * @param coneInnerAngle Size of the inner cone in degree
  61939. * @param coneOuterAngle Size of the outer cone in degree
  61940. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  61941. */
  61942. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  61943. if (coneOuterAngle < coneInnerAngle) {
  61944. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  61945. return;
  61946. }
  61947. this._coneInnerAngle = coneInnerAngle;
  61948. this._coneOuterAngle = coneOuterAngle;
  61949. this._coneOuterGain = coneOuterGain;
  61950. this._isDirectional = true;
  61951. if (this.isPlaying && this.loop) {
  61952. this.stop();
  61953. this.play();
  61954. }
  61955. };
  61956. Sound.prototype.setPosition = function (newPosition) {
  61957. this._position = newPosition;
  61958. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  61959. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  61960. }
  61961. };
  61962. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  61963. this._localDirection = newLocalDirection;
  61964. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  61965. this._updateDirection();
  61966. }
  61967. };
  61968. Sound.prototype._updateDirection = function () {
  61969. if (!this._connectedMesh || !this._soundPanner) {
  61970. return;
  61971. }
  61972. var mat = this._connectedMesh.getWorldMatrix();
  61973. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  61974. direction.normalize();
  61975. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  61976. };
  61977. Sound.prototype.updateDistanceFromListener = function () {
  61978. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  61979. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  61980. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  61981. }
  61982. };
  61983. Sound.prototype.setAttenuationFunction = function (callback) {
  61984. this._customAttenuationFunction = callback;
  61985. };
  61986. /**
  61987. * Play the sound
  61988. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  61989. * @param offset (optional) Start the sound setting it at a specific time
  61990. */
  61991. Sound.prototype.play = function (time, offset) {
  61992. var _this = this;
  61993. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  61994. try {
  61995. if (this._startOffset < 0) {
  61996. time = -this._startOffset;
  61997. this._startOffset = 0;
  61998. }
  61999. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62000. if (!this._soundSource || !this._streamingSource) {
  62001. if (this.spatialSound && this._soundPanner) {
  62002. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62003. if (this._isDirectional) {
  62004. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62005. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62006. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62007. if (this._connectedMesh) {
  62008. this._updateDirection();
  62009. }
  62010. else {
  62011. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62012. }
  62013. }
  62014. }
  62015. }
  62016. if (this._streaming) {
  62017. if (!this._streamingSource) {
  62018. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62019. this._htmlAudioElement.onended = function () { _this._onended(); };
  62020. this._htmlAudioElement.playbackRate = this._playbackRate;
  62021. }
  62022. this._streamingSource.disconnect();
  62023. this._streamingSource.connect(this._inputAudioNode);
  62024. if (this._htmlAudioElement) {
  62025. this._htmlAudioElement.play();
  62026. }
  62027. }
  62028. else {
  62029. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62030. this._soundSource.buffer = this._audioBuffer;
  62031. this._soundSource.connect(this._inputAudioNode);
  62032. this._soundSource.loop = this.loop;
  62033. this._soundSource.playbackRate.value = this._playbackRate;
  62034. this._soundSource.onended = function () { _this._onended(); };
  62035. if (this._soundSource.buffer) {
  62036. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62037. }
  62038. }
  62039. this._startTime = startTime;
  62040. this.isPlaying = true;
  62041. this.isPaused = false;
  62042. }
  62043. catch (ex) {
  62044. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62045. }
  62046. }
  62047. };
  62048. Sound.prototype._onended = function () {
  62049. this.isPlaying = false;
  62050. if (this.onended) {
  62051. this.onended();
  62052. }
  62053. };
  62054. /**
  62055. * Stop the sound
  62056. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62057. */
  62058. Sound.prototype.stop = function (time) {
  62059. if (this.isPlaying) {
  62060. if (this._streaming) {
  62061. if (this._htmlAudioElement) {
  62062. this._htmlAudioElement.pause();
  62063. // Test needed for Firefox or it will generate an Invalid State Error
  62064. if (this._htmlAudioElement.currentTime > 0) {
  62065. this._htmlAudioElement.currentTime = 0;
  62066. }
  62067. }
  62068. else {
  62069. this._streamingSource.disconnect();
  62070. }
  62071. }
  62072. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62073. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62074. this._soundSource.stop(stopTime);
  62075. this._soundSource.onended = function () { };
  62076. if (!this.isPaused) {
  62077. this._startOffset = 0;
  62078. }
  62079. }
  62080. this.isPlaying = false;
  62081. }
  62082. };
  62083. Sound.prototype.pause = function () {
  62084. if (this.isPlaying) {
  62085. this.isPaused = true;
  62086. if (this._streaming) {
  62087. if (this._htmlAudioElement) {
  62088. this._htmlAudioElement.pause();
  62089. }
  62090. else {
  62091. this._streamingSource.disconnect();
  62092. }
  62093. }
  62094. else if (BABYLON.Engine.audioEngine.audioContext) {
  62095. this.stop(0);
  62096. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62097. }
  62098. }
  62099. };
  62100. Sound.prototype.setVolume = function (newVolume, time) {
  62101. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62102. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62103. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62104. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62105. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62106. }
  62107. else {
  62108. this._soundGain.gain.value = newVolume;
  62109. }
  62110. }
  62111. this._volume = newVolume;
  62112. };
  62113. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62114. this._playbackRate = newPlaybackRate;
  62115. if (this.isPlaying) {
  62116. if (this._streaming && this._htmlAudioElement) {
  62117. this._htmlAudioElement.playbackRate = this._playbackRate;
  62118. }
  62119. else if (this._soundSource) {
  62120. this._soundSource.playbackRate.value = this._playbackRate;
  62121. }
  62122. }
  62123. };
  62124. Sound.prototype.getVolume = function () {
  62125. return this._volume;
  62126. };
  62127. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62128. var _this = this;
  62129. if (this._connectedMesh && this._registerFunc) {
  62130. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62131. this._registerFunc = null;
  62132. }
  62133. this._connectedMesh = meshToConnectTo;
  62134. if (!this.spatialSound) {
  62135. this.spatialSound = true;
  62136. this._createSpatialParameters();
  62137. if (this.isPlaying && this.loop) {
  62138. this.stop();
  62139. this.play();
  62140. }
  62141. }
  62142. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62143. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62144. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62145. };
  62146. Sound.prototype.detachFromMesh = function () {
  62147. if (this._connectedMesh && this._registerFunc) {
  62148. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62149. this._registerFunc = null;
  62150. this._connectedMesh = null;
  62151. }
  62152. };
  62153. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62154. if (!node.getBoundingInfo) {
  62155. return;
  62156. }
  62157. var mesh = node;
  62158. var boundingInfo = mesh.getBoundingInfo();
  62159. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62160. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62161. this._updateDirection();
  62162. }
  62163. };
  62164. Sound.prototype.clone = function () {
  62165. var _this = this;
  62166. if (!this._streaming) {
  62167. var setBufferAndRun = function () {
  62168. if (_this._isReadyToPlay) {
  62169. clonedSound._audioBuffer = _this.getAudioBuffer();
  62170. clonedSound._isReadyToPlay = true;
  62171. if (clonedSound.autoplay) {
  62172. clonedSound.play();
  62173. }
  62174. }
  62175. else {
  62176. window.setTimeout(setBufferAndRun, 300);
  62177. }
  62178. };
  62179. var currentOptions = {
  62180. autoplay: this.autoplay, loop: this.loop,
  62181. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62182. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62183. refDistance: this.refDistance, distanceModel: this.distanceModel
  62184. };
  62185. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62186. if (this.useCustomAttenuation) {
  62187. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62188. }
  62189. clonedSound.setPosition(this._position);
  62190. clonedSound.setPlaybackRate(this._playbackRate);
  62191. setBufferAndRun();
  62192. return clonedSound;
  62193. }
  62194. // Can't clone a streaming sound
  62195. else {
  62196. return null;
  62197. }
  62198. };
  62199. Sound.prototype.getAudioBuffer = function () {
  62200. return this._audioBuffer;
  62201. };
  62202. Sound.prototype.serialize = function () {
  62203. var serializationObject = {
  62204. name: this.name,
  62205. url: this.name,
  62206. autoplay: this.autoplay,
  62207. loop: this.loop,
  62208. volume: this._volume,
  62209. spatialSound: this.spatialSound,
  62210. maxDistance: this.maxDistance,
  62211. rolloffFactor: this.rolloffFactor,
  62212. refDistance: this.refDistance,
  62213. distanceModel: this.distanceModel,
  62214. playbackRate: this._playbackRate,
  62215. panningModel: this._panningModel,
  62216. soundTrackId: this.soundTrackId
  62217. };
  62218. if (this.spatialSound) {
  62219. if (this._connectedMesh)
  62220. serializationObject.connectedMeshId = this._connectedMesh.id;
  62221. serializationObject.position = this._position.asArray();
  62222. serializationObject.refDistance = this.refDistance;
  62223. serializationObject.distanceModel = this.distanceModel;
  62224. serializationObject.isDirectional = this._isDirectional;
  62225. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62226. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62227. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62228. serializationObject.coneOuterGain = this._coneOuterGain;
  62229. }
  62230. return serializationObject;
  62231. };
  62232. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62233. var soundName = parsedSound.name;
  62234. var soundUrl;
  62235. if (parsedSound.url) {
  62236. soundUrl = rootUrl + parsedSound.url;
  62237. }
  62238. else {
  62239. soundUrl = rootUrl + soundName;
  62240. }
  62241. var options = {
  62242. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62243. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62244. rolloffFactor: parsedSound.rolloffFactor,
  62245. refDistance: parsedSound.refDistance,
  62246. distanceModel: parsedSound.distanceModel,
  62247. playbackRate: parsedSound.playbackRate
  62248. };
  62249. var newSound;
  62250. if (!sourceSound) {
  62251. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62252. scene._addPendingData(newSound);
  62253. }
  62254. else {
  62255. var setBufferAndRun = function () {
  62256. if (sourceSound._isReadyToPlay) {
  62257. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62258. newSound._isReadyToPlay = true;
  62259. if (newSound.autoplay) {
  62260. newSound.play();
  62261. }
  62262. }
  62263. else {
  62264. window.setTimeout(setBufferAndRun, 300);
  62265. }
  62266. };
  62267. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62268. setBufferAndRun();
  62269. }
  62270. if (parsedSound.position) {
  62271. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62272. newSound.setPosition(soundPosition);
  62273. }
  62274. if (parsedSound.isDirectional) {
  62275. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62276. if (parsedSound.localDirectionToMesh) {
  62277. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62278. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62279. }
  62280. }
  62281. if (parsedSound.connectedMeshId) {
  62282. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62283. if (connectedMesh) {
  62284. newSound.attachToMesh(connectedMesh);
  62285. }
  62286. }
  62287. return newSound;
  62288. };
  62289. return Sound;
  62290. }());
  62291. BABYLON.Sound = Sound;
  62292. })(BABYLON || (BABYLON = {}));
  62293. //# sourceMappingURL=babylon.sound.js.map
  62294. var BABYLON;
  62295. (function (BABYLON) {
  62296. var SoundTrack = /** @class */ (function () {
  62297. function SoundTrack(scene, options) {
  62298. this.id = -1;
  62299. this._isMainTrack = false;
  62300. this._isInitialized = false;
  62301. this._scene = scene;
  62302. this.soundCollection = new Array();
  62303. this._options = options;
  62304. if (!this._isMainTrack) {
  62305. this._scene.soundTracks.push(this);
  62306. this.id = this._scene.soundTracks.length - 1;
  62307. }
  62308. }
  62309. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62310. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62311. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62312. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62313. if (this._options) {
  62314. if (this._options.volume) {
  62315. this._outputAudioNode.gain.value = this._options.volume;
  62316. }
  62317. if (this._options.mainTrack) {
  62318. this._isMainTrack = this._options.mainTrack;
  62319. }
  62320. }
  62321. this._isInitialized = true;
  62322. }
  62323. };
  62324. SoundTrack.prototype.dispose = function () {
  62325. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62326. if (this._connectedAnalyser) {
  62327. this._connectedAnalyser.stopDebugCanvas();
  62328. }
  62329. while (this.soundCollection.length) {
  62330. this.soundCollection[0].dispose();
  62331. }
  62332. if (this._outputAudioNode) {
  62333. this._outputAudioNode.disconnect();
  62334. }
  62335. this._outputAudioNode = null;
  62336. }
  62337. };
  62338. SoundTrack.prototype.AddSound = function (sound) {
  62339. if (!this._isInitialized) {
  62340. this._initializeSoundTrackAudioGraph();
  62341. }
  62342. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62343. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62344. }
  62345. if (sound.soundTrackId) {
  62346. if (sound.soundTrackId === -1) {
  62347. this._scene.mainSoundTrack.RemoveSound(sound);
  62348. }
  62349. else {
  62350. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62351. }
  62352. }
  62353. this.soundCollection.push(sound);
  62354. sound.soundTrackId = this.id;
  62355. };
  62356. SoundTrack.prototype.RemoveSound = function (sound) {
  62357. var index = this.soundCollection.indexOf(sound);
  62358. if (index !== -1) {
  62359. this.soundCollection.splice(index, 1);
  62360. }
  62361. };
  62362. SoundTrack.prototype.setVolume = function (newVolume) {
  62363. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62364. this._outputAudioNode.gain.value = newVolume;
  62365. }
  62366. };
  62367. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62368. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62369. for (var i = 0; i < this.soundCollection.length; i++) {
  62370. this.soundCollection[i].switchPanningModelToHRTF();
  62371. }
  62372. }
  62373. };
  62374. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62375. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62376. for (var i = 0; i < this.soundCollection.length; i++) {
  62377. this.soundCollection[i].switchPanningModelToEqualPower();
  62378. }
  62379. }
  62380. };
  62381. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62382. if (this._connectedAnalyser) {
  62383. this._connectedAnalyser.stopDebugCanvas();
  62384. }
  62385. this._connectedAnalyser = analyser;
  62386. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62387. this._outputAudioNode.disconnect();
  62388. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62389. }
  62390. };
  62391. return SoundTrack;
  62392. }());
  62393. BABYLON.SoundTrack = SoundTrack;
  62394. })(BABYLON || (BABYLON = {}));
  62395. //# sourceMappingURL=babylon.soundtrack.js.map
  62396. var BABYLON;
  62397. (function (BABYLON) {
  62398. /**
  62399. * Class used to work with sound analyzer using fast fourier transform (FFT)
  62400. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  62401. */
  62402. var Analyser = /** @class */ (function () {
  62403. /**
  62404. * Creates a new analyser
  62405. * @param scene defines hosting scene
  62406. */
  62407. function Analyser(scene) {
  62408. /**
  62409. * Gets or sets the smoothing
  62410. * @ignorenaming
  62411. */
  62412. this.SMOOTHING = 0.75;
  62413. /**
  62414. * Gets or sets the FFT table size
  62415. * @ignorenaming
  62416. */
  62417. this.FFT_SIZE = 512;
  62418. /**
  62419. * Gets or sets the bar graph amplitude
  62420. * @ignorenaming
  62421. */
  62422. this.BARGRAPHAMPLITUDE = 256;
  62423. /**
  62424. * Gets or sets the position of the debug canvas
  62425. * @ignorenaming
  62426. */
  62427. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62428. /**
  62429. * Gets or sets the debug canvas size
  62430. * @ignorenaming
  62431. */
  62432. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62433. this._scene = scene;
  62434. this._audioEngine = BABYLON.Engine.audioEngine;
  62435. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62436. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  62437. this._webAudioAnalyser.minDecibels = -140;
  62438. this._webAudioAnalyser.maxDecibels = 0;
  62439. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62440. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62441. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  62442. }
  62443. }
  62444. /**
  62445. * Get the number of data values you will have to play with for the visualization
  62446. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  62447. * @returns a number
  62448. */
  62449. Analyser.prototype.getFrequencyBinCount = function () {
  62450. if (this._audioEngine.canUseWebAudio) {
  62451. return this._webAudioAnalyser.frequencyBinCount;
  62452. }
  62453. else {
  62454. return 0;
  62455. }
  62456. };
  62457. /**
  62458. * Gets the current frequency data as a byte array
  62459. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62460. * @returns a Uint8Array
  62461. */
  62462. Analyser.prototype.getByteFrequencyData = function () {
  62463. if (this._audioEngine.canUseWebAudio) {
  62464. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62465. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62466. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  62467. }
  62468. return this._byteFreqs;
  62469. };
  62470. /**
  62471. * Gets the current waveform as a byte array
  62472. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  62473. * @returns a Uint8Array
  62474. */
  62475. Analyser.prototype.getByteTimeDomainData = function () {
  62476. if (this._audioEngine.canUseWebAudio) {
  62477. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62478. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62479. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  62480. }
  62481. return this._byteTime;
  62482. };
  62483. /**
  62484. * Gets the current frequency data as a float array
  62485. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62486. * @returns a Float32Array
  62487. */
  62488. Analyser.prototype.getFloatFrequencyData = function () {
  62489. if (this._audioEngine.canUseWebAudio) {
  62490. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62491. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62492. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  62493. }
  62494. return this._floatFreqs;
  62495. };
  62496. /**
  62497. * Renders the debug canvas
  62498. */
  62499. Analyser.prototype.drawDebugCanvas = function () {
  62500. var _this = this;
  62501. if (this._audioEngine.canUseWebAudio) {
  62502. if (!this._debugCanvas) {
  62503. this._debugCanvas = document.createElement("canvas");
  62504. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  62505. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  62506. this._debugCanvas.style.position = "absolute";
  62507. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  62508. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  62509. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  62510. document.body.appendChild(this._debugCanvas);
  62511. this._registerFunc = function () {
  62512. _this.drawDebugCanvas();
  62513. };
  62514. this._scene.registerBeforeRender(this._registerFunc);
  62515. }
  62516. if (this._registerFunc && this._debugCanvasContext) {
  62517. var workingArray = this.getByteFrequencyData();
  62518. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  62519. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  62520. // Draw the frequency domain chart.
  62521. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  62522. var value = workingArray[i];
  62523. var percent = value / this.BARGRAPHAMPLITUDE;
  62524. var height = this.DEBUGCANVASSIZE.height * percent;
  62525. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  62526. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  62527. var hue = i / this.getFrequencyBinCount() * 360;
  62528. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  62529. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  62530. }
  62531. }
  62532. }
  62533. };
  62534. /**
  62535. * Stops rendering the debug canvas and removes it
  62536. */
  62537. Analyser.prototype.stopDebugCanvas = function () {
  62538. if (this._debugCanvas) {
  62539. if (this._registerFunc) {
  62540. this._scene.unregisterBeforeRender(this._registerFunc);
  62541. this._registerFunc = null;
  62542. }
  62543. document.body.removeChild(this._debugCanvas);
  62544. this._debugCanvas = null;
  62545. this._debugCanvasContext = null;
  62546. }
  62547. };
  62548. /**
  62549. * Connects two audio nodes
  62550. * @param inputAudioNode defines first node to connect
  62551. * @param outputAudioNode defines second node to connect
  62552. */
  62553. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  62554. if (this._audioEngine.canUseWebAudio) {
  62555. inputAudioNode.connect(this._webAudioAnalyser);
  62556. this._webAudioAnalyser.connect(outputAudioNode);
  62557. }
  62558. };
  62559. /**
  62560. * Releases all associated resources
  62561. */
  62562. Analyser.prototype.dispose = function () {
  62563. if (this._audioEngine.canUseWebAudio) {
  62564. this._webAudioAnalyser.disconnect();
  62565. }
  62566. };
  62567. return Analyser;
  62568. }());
  62569. BABYLON.Analyser = Analyser;
  62570. })(BABYLON || (BABYLON = {}));
  62571. //# sourceMappingURL=babylon.analyser.js.map
  62572. var BABYLON;
  62573. (function (BABYLON) {
  62574. var CubeTexture = /** @class */ (function (_super) {
  62575. __extends(CubeTexture, _super);
  62576. /**
  62577. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  62578. * as prefiltered data.
  62579. * @param rootUrl defines the url of the texture or the root name of the six images
  62580. * @param scene defines the scene the texture is attached to
  62581. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  62582. * @param noMipmap defines if mipmaps should be created or not
  62583. * @param files defines the six files to load for the different faces
  62584. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  62585. * @param onError defines a callback triggered in case of error during load
  62586. * @param format defines the internal format to use for the texture once loaded
  62587. * @param prefiltered defines whether or not the texture is created from prefiltered data
  62588. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  62589. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  62590. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  62591. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  62592. * @return the cube texture
  62593. */
  62594. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  62595. if (extensions === void 0) { extensions = null; }
  62596. if (noMipmap === void 0) { noMipmap = false; }
  62597. if (files === void 0) { files = null; }
  62598. if (onLoad === void 0) { onLoad = null; }
  62599. if (onError === void 0) { onError = null; }
  62600. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  62601. if (prefiltered === void 0) { prefiltered = false; }
  62602. if (forcedExtension === void 0) { forcedExtension = null; }
  62603. if (createPolynomials === void 0) { createPolynomials = false; }
  62604. if (lodScale === void 0) { lodScale = 0.8; }
  62605. if (lodOffset === void 0) { lodOffset = 0; }
  62606. var _this = _super.call(this, scene) || this;
  62607. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62608. /**
  62609. * Gets or sets the center of the bounding box associated with the cube texture
  62610. * It must define where the camera used to render the texture was set
  62611. */
  62612. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62613. _this._rotationY = 0;
  62614. /** @hidden */
  62615. _this._prefiltered = false;
  62616. _this.name = rootUrl;
  62617. _this.url = rootUrl;
  62618. _this._noMipmap = noMipmap;
  62619. _this.hasAlpha = false;
  62620. _this._format = format;
  62621. _this.isCube = true;
  62622. _this._textureMatrix = BABYLON.Matrix.Identity();
  62623. _this._createPolynomials = createPolynomials;
  62624. if (!rootUrl && !files) {
  62625. return _this;
  62626. }
  62627. var lastDot = rootUrl.lastIndexOf(".");
  62628. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  62629. var isDDS = (extension === ".dds");
  62630. var isEnv = (extension === ".env");
  62631. if (isEnv) {
  62632. _this.gammaSpace = false;
  62633. _this._prefiltered = false;
  62634. }
  62635. else {
  62636. _this._prefiltered = prefiltered;
  62637. if (prefiltered) {
  62638. _this.gammaSpace = false;
  62639. }
  62640. }
  62641. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  62642. if (!files) {
  62643. if (!isEnv && !isDDS && !extensions) {
  62644. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  62645. }
  62646. files = [];
  62647. if (extensions) {
  62648. for (var index = 0; index < extensions.length; index++) {
  62649. files.push(rootUrl + extensions[index]);
  62650. }
  62651. }
  62652. }
  62653. _this._files = files;
  62654. if (!_this._texture) {
  62655. if (!scene.useDelayedTextureLoading) {
  62656. if (prefiltered) {
  62657. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  62658. }
  62659. else {
  62660. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  62661. }
  62662. }
  62663. else {
  62664. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  62665. }
  62666. }
  62667. else if (onLoad) {
  62668. if (_this._texture.isReady) {
  62669. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  62670. }
  62671. else {
  62672. _this._texture.onLoadedObservable.add(onLoad);
  62673. }
  62674. }
  62675. return _this;
  62676. }
  62677. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  62678. get: function () {
  62679. return this._boundingBoxSize;
  62680. },
  62681. /**
  62682. * Gets or sets the size of the bounding box associated with the cube texture
  62683. * When defined, the cubemap will switch to local mode
  62684. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  62685. * @example https://www.babylonjs-playground.com/#RNASML
  62686. */
  62687. set: function (value) {
  62688. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  62689. return;
  62690. }
  62691. this._boundingBoxSize = value;
  62692. var scene = this.getScene();
  62693. if (scene) {
  62694. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  62695. }
  62696. },
  62697. enumerable: true,
  62698. configurable: true
  62699. });
  62700. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  62701. /**
  62702. * Gets texture matrix rotation angle around Y axis radians.
  62703. */
  62704. get: function () {
  62705. return this._rotationY;
  62706. },
  62707. /**
  62708. * Sets texture matrix rotation angle around Y axis in radians.
  62709. */
  62710. set: function (value) {
  62711. this._rotationY = value;
  62712. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  62713. },
  62714. enumerable: true,
  62715. configurable: true
  62716. });
  62717. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  62718. var rootUrlKey = "";
  62719. files.forEach(function (url) { return rootUrlKey += url; });
  62720. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  62721. };
  62722. /**
  62723. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  62724. * @param url defines the url of the prefiltered texture
  62725. * @param scene defines the scene the texture is attached to
  62726. * @param forcedExtension defines the extension of the file if different from the url
  62727. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  62728. * @return the prefiltered texture
  62729. */
  62730. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  62731. if (forcedExtension === void 0) { forcedExtension = null; }
  62732. if (createPolynomials === void 0) { createPolynomials = true; }
  62733. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  62734. };
  62735. // Methods
  62736. CubeTexture.prototype.delayLoad = function () {
  62737. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  62738. return;
  62739. }
  62740. var scene = this.getScene();
  62741. if (!scene) {
  62742. return;
  62743. }
  62744. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  62745. this._texture = this._getFromCache(this.url, this._noMipmap);
  62746. if (!this._texture) {
  62747. if (this._prefiltered) {
  62748. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  62749. }
  62750. else {
  62751. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  62752. }
  62753. }
  62754. };
  62755. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  62756. return this._textureMatrix;
  62757. };
  62758. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  62759. this._textureMatrix = value;
  62760. };
  62761. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  62762. var texture = BABYLON.SerializationHelper.Parse(function () {
  62763. var prefiltered = false;
  62764. if (parsedTexture.prefiltered) {
  62765. prefiltered = parsedTexture.prefiltered;
  62766. }
  62767. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  62768. }, parsedTexture, scene);
  62769. // Local Cubemaps
  62770. if (parsedTexture.boundingBoxPosition) {
  62771. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  62772. }
  62773. if (parsedTexture.boundingBoxSize) {
  62774. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  62775. }
  62776. // Animations
  62777. if (parsedTexture.animations) {
  62778. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  62779. var parsedAnimation = parsedTexture.animations[animationIndex];
  62780. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  62781. }
  62782. }
  62783. return texture;
  62784. };
  62785. CubeTexture.prototype.clone = function () {
  62786. var _this = this;
  62787. return BABYLON.SerializationHelper.Clone(function () {
  62788. var scene = _this.getScene();
  62789. if (!scene) {
  62790. return _this;
  62791. }
  62792. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  62793. }, this);
  62794. };
  62795. __decorate([
  62796. BABYLON.serialize("rotationY")
  62797. ], CubeTexture.prototype, "_rotationY", void 0);
  62798. return CubeTexture;
  62799. }(BABYLON.BaseTexture));
  62800. BABYLON.CubeTexture = CubeTexture;
  62801. })(BABYLON || (BABYLON = {}));
  62802. //# sourceMappingURL=babylon.cubeTexture.js.map
  62803. var BABYLON;
  62804. (function (BABYLON) {
  62805. var RenderTargetTexture = /** @class */ (function (_super) {
  62806. __extends(RenderTargetTexture, _super);
  62807. /**
  62808. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  62809. * or used a shadow, depth texture...
  62810. * @param name The friendly name of the texture
  62811. * @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)
  62812. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  62813. * @param generateMipMaps True if mip maps need to be generated after render.
  62814. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  62815. * @param type The type of the buffer in the RTT (int, half float, float...)
  62816. * @param isCube True if a cube texture needs to be created
  62817. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  62818. * @param generateDepthBuffer True to generate a depth buffer
  62819. * @param generateStencilBuffer True to generate a stencil buffer
  62820. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  62821. */
  62822. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  62823. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  62824. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62825. if (isCube === void 0) { isCube = false; }
  62826. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62827. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  62828. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  62829. if (isMulti === void 0) { isMulti = false; }
  62830. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  62831. _this.isCube = isCube;
  62832. /**
  62833. * Use this list to define the list of mesh you want to render.
  62834. */
  62835. _this.renderList = new Array();
  62836. _this.renderParticles = true;
  62837. _this.renderSprites = false;
  62838. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  62839. _this.ignoreCameraViewport = false;
  62840. // Events
  62841. /**
  62842. * An event triggered when the texture is unbind.
  62843. */
  62844. _this.onBeforeBindObservable = new BABYLON.Observable();
  62845. /**
  62846. * An event triggered when the texture is unbind.
  62847. */
  62848. _this.onAfterUnbindObservable = new BABYLON.Observable();
  62849. /**
  62850. * An event triggered before rendering the texture
  62851. */
  62852. _this.onBeforeRenderObservable = new BABYLON.Observable();
  62853. /**
  62854. * An event triggered after rendering the texture
  62855. */
  62856. _this.onAfterRenderObservable = new BABYLON.Observable();
  62857. /**
  62858. * An event triggered after the texture clear
  62859. */
  62860. _this.onClearObservable = new BABYLON.Observable();
  62861. _this._currentRefreshId = -1;
  62862. _this._refreshRate = 1;
  62863. _this._samples = 1;
  62864. /**
  62865. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  62866. * It must define where the camera used to render the texture is set
  62867. */
  62868. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62869. scene = _this.getScene();
  62870. if (!scene) {
  62871. return _this;
  62872. }
  62873. _this._engine = scene.getEngine();
  62874. _this.name = name;
  62875. _this.isRenderTarget = true;
  62876. _this._initialSizeParameter = size;
  62877. _this._processSizeParameter(size);
  62878. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  62879. });
  62880. _this._generateMipMaps = generateMipMaps ? true : false;
  62881. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  62882. // Rendering groups
  62883. _this._renderingManager = new BABYLON.RenderingManager(scene);
  62884. if (isMulti) {
  62885. return _this;
  62886. }
  62887. _this._renderTargetOptions = {
  62888. generateMipMaps: generateMipMaps,
  62889. type: type,
  62890. samplingMode: samplingMode,
  62891. generateDepthBuffer: generateDepthBuffer,
  62892. generateStencilBuffer: generateStencilBuffer
  62893. };
  62894. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  62895. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62896. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62897. }
  62898. if (isCube) {
  62899. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  62900. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  62901. _this._textureMatrix = BABYLON.Matrix.Identity();
  62902. }
  62903. else {
  62904. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  62905. }
  62906. return _this;
  62907. }
  62908. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  62909. get: function () {
  62910. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  62911. },
  62912. enumerable: true,
  62913. configurable: true
  62914. });
  62915. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  62916. get: function () {
  62917. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  62918. },
  62919. enumerable: true,
  62920. configurable: true
  62921. });
  62922. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  62923. get: function () {
  62924. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  62925. },
  62926. enumerable: true,
  62927. configurable: true
  62928. });
  62929. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  62930. set: function (callback) {
  62931. if (this._onAfterUnbindObserver) {
  62932. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  62933. }
  62934. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  62935. },
  62936. enumerable: true,
  62937. configurable: true
  62938. });
  62939. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  62940. set: function (callback) {
  62941. if (this._onBeforeRenderObserver) {
  62942. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  62943. }
  62944. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  62945. },
  62946. enumerable: true,
  62947. configurable: true
  62948. });
  62949. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  62950. set: function (callback) {
  62951. if (this._onAfterRenderObserver) {
  62952. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  62953. }
  62954. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  62955. },
  62956. enumerable: true,
  62957. configurable: true
  62958. });
  62959. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  62960. set: function (callback) {
  62961. if (this._onClearObserver) {
  62962. this.onClearObservable.remove(this._onClearObserver);
  62963. }
  62964. this._onClearObserver = this.onClearObservable.add(callback);
  62965. },
  62966. enumerable: true,
  62967. configurable: true
  62968. });
  62969. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  62970. get: function () {
  62971. return this._renderTargetOptions;
  62972. },
  62973. enumerable: true,
  62974. configurable: true
  62975. });
  62976. RenderTargetTexture.prototype._onRatioRescale = function () {
  62977. if (this._sizeRatio) {
  62978. this.resize(this._initialSizeParameter);
  62979. }
  62980. };
  62981. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  62982. get: function () {
  62983. return this._boundingBoxSize;
  62984. },
  62985. /**
  62986. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  62987. * When defined, the cubemap will switch to local mode
  62988. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  62989. * @example https://www.babylonjs-playground.com/#RNASML
  62990. */
  62991. set: function (value) {
  62992. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  62993. return;
  62994. }
  62995. this._boundingBoxSize = value;
  62996. var scene = this.getScene();
  62997. if (scene) {
  62998. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  62999. }
  63000. },
  63001. enumerable: true,
  63002. configurable: true
  63003. });
  63004. /**
  63005. * Creates a depth stencil texture.
  63006. * This is only available in WebGL 2 or with the depth texture extension available.
  63007. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63008. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63009. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63010. */
  63011. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63012. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63013. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63014. if (generateStencil === void 0) { generateStencil = false; }
  63015. if (!this.getScene()) {
  63016. return;
  63017. }
  63018. var engine = this.getScene().getEngine();
  63019. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63020. bilinearFiltering: bilinearFiltering,
  63021. comparisonFunction: comparisonFunction,
  63022. generateStencil: generateStencil,
  63023. isCube: this.isCube
  63024. });
  63025. engine.setFrameBufferDepthStencilTexture(this);
  63026. };
  63027. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63028. if (size.ratio) {
  63029. this._sizeRatio = size.ratio;
  63030. this._size = {
  63031. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63032. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63033. };
  63034. }
  63035. else {
  63036. this._size = size;
  63037. }
  63038. };
  63039. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63040. get: function () {
  63041. return this._samples;
  63042. },
  63043. set: function (value) {
  63044. if (this._samples === value) {
  63045. return;
  63046. }
  63047. var scene = this.getScene();
  63048. if (!scene) {
  63049. return;
  63050. }
  63051. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63052. },
  63053. enumerable: true,
  63054. configurable: true
  63055. });
  63056. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63057. this._currentRefreshId = -1;
  63058. };
  63059. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63060. get: function () {
  63061. return this._refreshRate;
  63062. },
  63063. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63064. set: function (value) {
  63065. this._refreshRate = value;
  63066. this.resetRefreshCounter();
  63067. },
  63068. enumerable: true,
  63069. configurable: true
  63070. });
  63071. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63072. if (!this._postProcessManager) {
  63073. var scene = this.getScene();
  63074. if (!scene) {
  63075. return;
  63076. }
  63077. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63078. this._postProcesses = new Array();
  63079. }
  63080. this._postProcesses.push(postProcess);
  63081. this._postProcesses[0].autoClear = false;
  63082. };
  63083. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63084. if (!this._postProcesses) {
  63085. return;
  63086. }
  63087. if (dispose) {
  63088. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63089. var postProcess = _a[_i];
  63090. postProcess.dispose();
  63091. }
  63092. }
  63093. this._postProcesses = [];
  63094. };
  63095. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63096. if (!this._postProcesses) {
  63097. return;
  63098. }
  63099. var index = this._postProcesses.indexOf(postProcess);
  63100. if (index === -1) {
  63101. return;
  63102. }
  63103. this._postProcesses.splice(index, 1);
  63104. if (this._postProcesses.length > 0) {
  63105. this._postProcesses[0].autoClear = false;
  63106. }
  63107. };
  63108. RenderTargetTexture.prototype._shouldRender = function () {
  63109. if (this._currentRefreshId === -1) { // At least render once
  63110. this._currentRefreshId = 1;
  63111. return true;
  63112. }
  63113. if (this.refreshRate === this._currentRefreshId) {
  63114. this._currentRefreshId = 1;
  63115. return true;
  63116. }
  63117. this._currentRefreshId++;
  63118. return false;
  63119. };
  63120. RenderTargetTexture.prototype.getRenderSize = function () {
  63121. if (this._size.width) {
  63122. return this._size.width;
  63123. }
  63124. return this._size;
  63125. };
  63126. RenderTargetTexture.prototype.getRenderWidth = function () {
  63127. if (this._size.width) {
  63128. return this._size.width;
  63129. }
  63130. return this._size;
  63131. };
  63132. RenderTargetTexture.prototype.getRenderHeight = function () {
  63133. if (this._size.width) {
  63134. return this._size.height;
  63135. }
  63136. return this._size;
  63137. };
  63138. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63139. get: function () {
  63140. return true;
  63141. },
  63142. enumerable: true,
  63143. configurable: true
  63144. });
  63145. RenderTargetTexture.prototype.scale = function (ratio) {
  63146. var newSize = this.getRenderSize() * ratio;
  63147. this.resize(newSize);
  63148. };
  63149. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63150. if (this.isCube) {
  63151. return this._textureMatrix;
  63152. }
  63153. return _super.prototype.getReflectionTextureMatrix.call(this);
  63154. };
  63155. RenderTargetTexture.prototype.resize = function (size) {
  63156. this.releaseInternalTexture();
  63157. var scene = this.getScene();
  63158. if (!scene) {
  63159. return;
  63160. }
  63161. this._processSizeParameter(size);
  63162. if (this.isCube) {
  63163. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63164. }
  63165. else {
  63166. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63167. }
  63168. };
  63169. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63170. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63171. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63172. var scene = this.getScene();
  63173. if (!scene) {
  63174. return;
  63175. }
  63176. var engine = scene.getEngine();
  63177. if (this.useCameraPostProcesses !== undefined) {
  63178. useCameraPostProcess = this.useCameraPostProcesses;
  63179. }
  63180. if (this._waitingRenderList) {
  63181. this.renderList = [];
  63182. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63183. var id = this._waitingRenderList[index];
  63184. var mesh_1 = scene.getMeshByID(id);
  63185. if (mesh_1) {
  63186. this.renderList.push(mesh_1);
  63187. }
  63188. }
  63189. delete this._waitingRenderList;
  63190. }
  63191. // Is predicate defined?
  63192. if (this.renderListPredicate) {
  63193. if (this.renderList) {
  63194. this.renderList.splice(0); // Clear previous renderList
  63195. }
  63196. else {
  63197. this.renderList = [];
  63198. }
  63199. var scene = this.getScene();
  63200. if (!scene) {
  63201. return;
  63202. }
  63203. var sceneMeshes = scene.meshes;
  63204. for (var index = 0; index < sceneMeshes.length; index++) {
  63205. var mesh = sceneMeshes[index];
  63206. if (this.renderListPredicate(mesh)) {
  63207. this.renderList.push(mesh);
  63208. }
  63209. }
  63210. }
  63211. this.onBeforeBindObservable.notifyObservers(this);
  63212. // Set custom projection.
  63213. // Needs to be before binding to prevent changing the aspect ratio.
  63214. var camera;
  63215. if (this.activeCamera) {
  63216. camera = this.activeCamera;
  63217. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63218. if (this.activeCamera !== scene.activeCamera) {
  63219. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63220. }
  63221. }
  63222. else {
  63223. camera = scene.activeCamera;
  63224. if (camera) {
  63225. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63226. }
  63227. }
  63228. // Prepare renderingManager
  63229. this._renderingManager.reset();
  63230. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63231. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63232. var sceneRenderId = scene.getRenderId();
  63233. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63234. var mesh = currentRenderList[meshIndex];
  63235. if (mesh) {
  63236. if (!mesh.isReady(this.refreshRate === 0)) {
  63237. this.resetRefreshCounter();
  63238. continue;
  63239. }
  63240. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63241. var isMasked = void 0;
  63242. if (!this.renderList && camera) {
  63243. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63244. }
  63245. else {
  63246. isMasked = false;
  63247. }
  63248. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63249. mesh._activate(sceneRenderId);
  63250. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63251. var subMesh = mesh.subMeshes[subIndex];
  63252. scene._activeIndices.addCount(subMesh.indexCount, false);
  63253. this._renderingManager.dispatch(subMesh, mesh);
  63254. }
  63255. }
  63256. }
  63257. }
  63258. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63259. var particleSystem = scene.particleSystems[particleIndex];
  63260. var emitter = particleSystem.emitter;
  63261. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63262. continue;
  63263. }
  63264. if (currentRenderList.indexOf(emitter) >= 0) {
  63265. this._renderingManager.dispatchParticles(particleSystem);
  63266. }
  63267. }
  63268. if (this.isCube) {
  63269. for (var face = 0; face < 6; face++) {
  63270. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63271. scene.incrementRenderId();
  63272. scene.resetCachedMaterial();
  63273. }
  63274. }
  63275. else {
  63276. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63277. }
  63278. this.onAfterUnbindObservable.notifyObservers(this);
  63279. if (scene.activeCamera) {
  63280. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63281. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63282. }
  63283. engine.setViewport(scene.activeCamera.viewport);
  63284. }
  63285. scene.resetCachedMaterial();
  63286. };
  63287. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63288. var minimum = 128;
  63289. var x = renderDimension * scale;
  63290. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63291. // Ensure we don't exceed the render dimension (while staying POT)
  63292. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63293. };
  63294. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63295. var _this = this;
  63296. if (!this._texture) {
  63297. return;
  63298. }
  63299. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63300. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63301. });
  63302. };
  63303. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63304. var scene = this.getScene();
  63305. if (!scene) {
  63306. return;
  63307. }
  63308. var engine = scene.getEngine();
  63309. if (!this._texture) {
  63310. return;
  63311. }
  63312. // Bind
  63313. if (this._postProcessManager) {
  63314. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63315. }
  63316. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63317. if (this._texture) {
  63318. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63319. }
  63320. }
  63321. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63322. // Clear
  63323. if (this.onClearObservable.hasObservers()) {
  63324. this.onClearObservable.notifyObservers(engine);
  63325. }
  63326. else {
  63327. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63328. }
  63329. if (!this._doNotChangeAspectRatio) {
  63330. scene.updateTransformMatrix(true);
  63331. }
  63332. // Render
  63333. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63334. if (this._postProcessManager) {
  63335. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63336. }
  63337. else if (useCameraPostProcess) {
  63338. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63339. }
  63340. if (!this._doNotChangeAspectRatio) {
  63341. scene.updateTransformMatrix(true);
  63342. }
  63343. // Dump ?
  63344. if (dumpForDebug) {
  63345. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63346. }
  63347. // Unbind
  63348. if (!this.isCube || faceIndex === 5) {
  63349. if (this.isCube) {
  63350. if (faceIndex === 5) {
  63351. engine.generateMipMapsForCubemap(this._texture);
  63352. }
  63353. }
  63354. this.unbindFrameBuffer(engine, faceIndex);
  63355. }
  63356. else {
  63357. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63358. }
  63359. };
  63360. /**
  63361. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63362. * This allowed control for front to back rendering or reversly depending of the special needs.
  63363. *
  63364. * @param renderingGroupId The rendering group id corresponding to its index
  63365. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63366. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63367. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63368. */
  63369. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63370. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63371. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63372. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63373. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63374. };
  63375. /**
  63376. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63377. *
  63378. * @param renderingGroupId The rendering group id corresponding to its index
  63379. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63380. */
  63381. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63382. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63383. };
  63384. RenderTargetTexture.prototype.clone = function () {
  63385. var textureSize = this.getSize();
  63386. 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);
  63387. // Base texture
  63388. newTexture.hasAlpha = this.hasAlpha;
  63389. newTexture.level = this.level;
  63390. // RenderTarget Texture
  63391. newTexture.coordinatesMode = this.coordinatesMode;
  63392. if (this.renderList) {
  63393. newTexture.renderList = this.renderList.slice(0);
  63394. }
  63395. return newTexture;
  63396. };
  63397. RenderTargetTexture.prototype.serialize = function () {
  63398. if (!this.name) {
  63399. return null;
  63400. }
  63401. var serializationObject = _super.prototype.serialize.call(this);
  63402. serializationObject.renderTargetSize = this.getRenderSize();
  63403. serializationObject.renderList = [];
  63404. if (this.renderList) {
  63405. for (var index = 0; index < this.renderList.length; index++) {
  63406. serializationObject.renderList.push(this.renderList[index].id);
  63407. }
  63408. }
  63409. return serializationObject;
  63410. };
  63411. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63412. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63413. var objBuffer = this.getInternalTexture();
  63414. var scene = this.getScene();
  63415. if (objBuffer && scene) {
  63416. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63417. }
  63418. };
  63419. RenderTargetTexture.prototype.dispose = function () {
  63420. if (this._postProcessManager) {
  63421. this._postProcessManager.dispose();
  63422. this._postProcessManager = null;
  63423. }
  63424. this.clearPostProcesses(true);
  63425. if (this._resizeObserver) {
  63426. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63427. this._resizeObserver = null;
  63428. }
  63429. this.renderList = null;
  63430. // Remove from custom render targets
  63431. var scene = this.getScene();
  63432. if (!scene) {
  63433. return;
  63434. }
  63435. var index = scene.customRenderTargets.indexOf(this);
  63436. if (index >= 0) {
  63437. scene.customRenderTargets.splice(index, 1);
  63438. }
  63439. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  63440. var camera = _a[_i];
  63441. index = camera.customRenderTargets.indexOf(this);
  63442. if (index >= 0) {
  63443. camera.customRenderTargets.splice(index, 1);
  63444. }
  63445. }
  63446. _super.prototype.dispose.call(this);
  63447. };
  63448. RenderTargetTexture.prototype._rebuild = function () {
  63449. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63450. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63451. }
  63452. if (this._postProcessManager) {
  63453. this._postProcessManager._rebuild();
  63454. }
  63455. };
  63456. /**
  63457. * Clear the info related to rendering groups preventing retention point in material dispose.
  63458. */
  63459. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  63460. if (this._renderingManager) {
  63461. this._renderingManager.freeRenderingGroups();
  63462. }
  63463. };
  63464. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  63465. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  63466. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  63467. return RenderTargetTexture;
  63468. }(BABYLON.Texture));
  63469. BABYLON.RenderTargetTexture = RenderTargetTexture;
  63470. })(BABYLON || (BABYLON = {}));
  63471. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  63472. var BABYLON;
  63473. (function (BABYLON) {
  63474. ;
  63475. var MultiRenderTarget = /** @class */ (function (_super) {
  63476. __extends(MultiRenderTarget, _super);
  63477. function MultiRenderTarget(name, size, count, scene, options) {
  63478. var _this = this;
  63479. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  63480. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  63481. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  63482. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  63483. _this._engine = scene.getEngine();
  63484. if (!_this.isSupported) {
  63485. _this.dispose();
  63486. return;
  63487. }
  63488. var types = [];
  63489. var samplingModes = [];
  63490. for (var i = 0; i < count; i++) {
  63491. if (options && options.types && options.types[i] !== undefined) {
  63492. types.push(options.types[i]);
  63493. }
  63494. else {
  63495. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63496. }
  63497. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  63498. samplingModes.push(options.samplingModes[i]);
  63499. }
  63500. else {
  63501. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63502. }
  63503. }
  63504. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  63505. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  63506. _this._size = size;
  63507. _this._multiRenderTargetOptions = {
  63508. samplingModes: samplingModes,
  63509. generateMipMaps: generateMipMaps,
  63510. generateDepthBuffer: generateDepthBuffer,
  63511. generateStencilBuffer: generateStencilBuffer,
  63512. generateDepthTexture: generateDepthTexture,
  63513. types: types,
  63514. textureCount: count
  63515. };
  63516. _this._createInternalTextures();
  63517. _this._createTextures();
  63518. return _this;
  63519. }
  63520. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  63521. get: function () {
  63522. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  63523. },
  63524. enumerable: true,
  63525. configurable: true
  63526. });
  63527. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  63528. get: function () {
  63529. return this._textures;
  63530. },
  63531. enumerable: true,
  63532. configurable: true
  63533. });
  63534. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  63535. get: function () {
  63536. return this._textures[this._textures.length - 1];
  63537. },
  63538. enumerable: true,
  63539. configurable: true
  63540. });
  63541. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  63542. set: function (wrap) {
  63543. if (this._textures) {
  63544. for (var i = 0; i < this._textures.length; i++) {
  63545. this._textures[i].wrapU = wrap;
  63546. }
  63547. }
  63548. },
  63549. enumerable: true,
  63550. configurable: true
  63551. });
  63552. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  63553. set: function (wrap) {
  63554. if (this._textures) {
  63555. for (var i = 0; i < this._textures.length; i++) {
  63556. this._textures[i].wrapV = wrap;
  63557. }
  63558. }
  63559. },
  63560. enumerable: true,
  63561. configurable: true
  63562. });
  63563. MultiRenderTarget.prototype._rebuild = function () {
  63564. this.releaseInternalTextures();
  63565. this._createInternalTextures();
  63566. for (var i = 0; i < this._internalTextures.length; i++) {
  63567. var texture = this._textures[i];
  63568. texture._texture = this._internalTextures[i];
  63569. }
  63570. // Keeps references to frame buffer and stencil/depth buffer
  63571. this._texture = this._internalTextures[0];
  63572. };
  63573. MultiRenderTarget.prototype._createInternalTextures = function () {
  63574. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  63575. };
  63576. MultiRenderTarget.prototype._createTextures = function () {
  63577. this._textures = [];
  63578. for (var i = 0; i < this._internalTextures.length; i++) {
  63579. var texture = new BABYLON.Texture(null, this.getScene());
  63580. texture._texture = this._internalTextures[i];
  63581. this._textures.push(texture);
  63582. }
  63583. // Keeps references to frame buffer and stencil/depth buffer
  63584. this._texture = this._internalTextures[0];
  63585. };
  63586. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  63587. get: function () {
  63588. return this._samples;
  63589. },
  63590. set: function (value) {
  63591. if (this._samples === value) {
  63592. return;
  63593. }
  63594. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  63595. },
  63596. enumerable: true,
  63597. configurable: true
  63598. });
  63599. MultiRenderTarget.prototype.resize = function (size) {
  63600. this.releaseInternalTextures();
  63601. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  63602. this._createInternalTextures();
  63603. };
  63604. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63605. var _this = this;
  63606. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  63607. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63608. });
  63609. };
  63610. MultiRenderTarget.prototype.dispose = function () {
  63611. this.releaseInternalTextures();
  63612. _super.prototype.dispose.call(this);
  63613. };
  63614. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  63615. if (!this._internalTextures) {
  63616. return;
  63617. }
  63618. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  63619. if (this._internalTextures[i] !== undefined) {
  63620. this._internalTextures[i].dispose();
  63621. this._internalTextures.splice(i, 1);
  63622. }
  63623. }
  63624. };
  63625. return MultiRenderTarget;
  63626. }(BABYLON.RenderTargetTexture));
  63627. BABYLON.MultiRenderTarget = MultiRenderTarget;
  63628. })(BABYLON || (BABYLON = {}));
  63629. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  63630. var BABYLON;
  63631. (function (BABYLON) {
  63632. var MirrorTexture = /** @class */ (function (_super) {
  63633. __extends(MirrorTexture, _super);
  63634. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  63635. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63636. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63637. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63638. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  63639. _this.scene = scene;
  63640. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  63641. _this._transformMatrix = BABYLON.Matrix.Zero();
  63642. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  63643. _this._adaptiveBlurKernel = 0;
  63644. _this._blurKernelX = 0;
  63645. _this._blurKernelY = 0;
  63646. _this._blurRatio = 1.0;
  63647. _this.ignoreCameraViewport = true;
  63648. _this._updateGammaSpace();
  63649. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  63650. _this._updateGammaSpace;
  63651. });
  63652. _this.onBeforeRenderObservable.add(function () {
  63653. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  63654. _this._savedViewMatrix = scene.getViewMatrix();
  63655. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  63656. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  63657. scene.clipPlane = _this.mirrorPlane;
  63658. scene.getEngine().cullBackFaces = false;
  63659. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  63660. });
  63661. _this.onAfterRenderObservable.add(function () {
  63662. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  63663. scene.getEngine().cullBackFaces = true;
  63664. scene._mirroredCameraPosition = null;
  63665. delete scene.clipPlane;
  63666. });
  63667. return _this;
  63668. }
  63669. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  63670. get: function () {
  63671. return this._blurRatio;
  63672. },
  63673. set: function (value) {
  63674. if (this._blurRatio === value) {
  63675. return;
  63676. }
  63677. this._blurRatio = value;
  63678. this._preparePostProcesses();
  63679. },
  63680. enumerable: true,
  63681. configurable: true
  63682. });
  63683. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  63684. set: function (value) {
  63685. this._adaptiveBlurKernel = value;
  63686. this._autoComputeBlurKernel();
  63687. },
  63688. enumerable: true,
  63689. configurable: true
  63690. });
  63691. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  63692. set: function (value) {
  63693. this.blurKernelX = value;
  63694. this.blurKernelY = value;
  63695. },
  63696. enumerable: true,
  63697. configurable: true
  63698. });
  63699. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  63700. get: function () {
  63701. return this._blurKernelX;
  63702. },
  63703. set: function (value) {
  63704. if (this._blurKernelX === value) {
  63705. return;
  63706. }
  63707. this._blurKernelX = value;
  63708. this._preparePostProcesses();
  63709. },
  63710. enumerable: true,
  63711. configurable: true
  63712. });
  63713. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  63714. get: function () {
  63715. return this._blurKernelY;
  63716. },
  63717. set: function (value) {
  63718. if (this._blurKernelY === value) {
  63719. return;
  63720. }
  63721. this._blurKernelY = value;
  63722. this._preparePostProcesses();
  63723. },
  63724. enumerable: true,
  63725. configurable: true
  63726. });
  63727. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  63728. var engine = this.getScene().getEngine();
  63729. var dw = this.getRenderWidth() / engine.getRenderWidth();
  63730. var dh = this.getRenderHeight() / engine.getRenderHeight();
  63731. this.blurKernelX = this._adaptiveBlurKernel * dw;
  63732. this.blurKernelY = this._adaptiveBlurKernel * dh;
  63733. };
  63734. MirrorTexture.prototype._onRatioRescale = function () {
  63735. if (this._sizeRatio) {
  63736. this.resize(this._initialSizeParameter);
  63737. if (!this._adaptiveBlurKernel) {
  63738. this._preparePostProcesses();
  63739. }
  63740. }
  63741. if (this._adaptiveBlurKernel) {
  63742. this._autoComputeBlurKernel();
  63743. }
  63744. };
  63745. MirrorTexture.prototype._updateGammaSpace = function () {
  63746. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  63747. };
  63748. MirrorTexture.prototype._preparePostProcesses = function () {
  63749. this.clearPostProcesses(true);
  63750. if (this._blurKernelX && this._blurKernelY) {
  63751. var engine = this.getScene().getEngine();
  63752. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63753. 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);
  63754. this._blurX.autoClear = false;
  63755. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  63756. this._blurX.inputTexture = this._texture;
  63757. }
  63758. else {
  63759. this._blurX.alwaysForcePOT = true;
  63760. }
  63761. 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);
  63762. this._blurY.autoClear = false;
  63763. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  63764. this.addPostProcess(this._blurX);
  63765. this.addPostProcess(this._blurY);
  63766. }
  63767. else {
  63768. if (this._blurY) {
  63769. this.removePostProcess(this._blurY);
  63770. this._blurY.dispose();
  63771. this._blurY = null;
  63772. }
  63773. if (this._blurX) {
  63774. this.removePostProcess(this._blurX);
  63775. this._blurX.dispose();
  63776. this._blurX = null;
  63777. }
  63778. }
  63779. };
  63780. MirrorTexture.prototype.clone = function () {
  63781. var scene = this.getScene();
  63782. if (!scene) {
  63783. return this;
  63784. }
  63785. var textureSize = this.getSize();
  63786. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  63787. // Base texture
  63788. newTexture.hasAlpha = this.hasAlpha;
  63789. newTexture.level = this.level;
  63790. // Mirror Texture
  63791. newTexture.mirrorPlane = this.mirrorPlane.clone();
  63792. if (this.renderList) {
  63793. newTexture.renderList = this.renderList.slice(0);
  63794. }
  63795. return newTexture;
  63796. };
  63797. MirrorTexture.prototype.serialize = function () {
  63798. if (!this.name) {
  63799. return null;
  63800. }
  63801. var serializationObject = _super.prototype.serialize.call(this);
  63802. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  63803. return serializationObject;
  63804. };
  63805. MirrorTexture.prototype.dispose = function () {
  63806. _super.prototype.dispose.call(this);
  63807. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  63808. };
  63809. return MirrorTexture;
  63810. }(BABYLON.RenderTargetTexture));
  63811. BABYLON.MirrorTexture = MirrorTexture;
  63812. })(BABYLON || (BABYLON = {}));
  63813. //# sourceMappingURL=babylon.mirrorTexture.js.map
  63814. var BABYLON;
  63815. (function (BABYLON) {
  63816. /**
  63817. * Creates a refraction texture used by refraction channel of the standard material.
  63818. * @param name the texture name
  63819. * @param size size of the underlying texture
  63820. * @param scene root scene
  63821. */
  63822. var RefractionTexture = /** @class */ (function (_super) {
  63823. __extends(RefractionTexture, _super);
  63824. function RefractionTexture(name, size, scene, generateMipMaps) {
  63825. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  63826. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  63827. _this.depth = 2.0;
  63828. _this.onBeforeRenderObservable.add(function () {
  63829. scene.clipPlane = _this.refractionPlane;
  63830. });
  63831. _this.onAfterRenderObservable.add(function () {
  63832. delete scene.clipPlane;
  63833. });
  63834. return _this;
  63835. }
  63836. RefractionTexture.prototype.clone = function () {
  63837. var scene = this.getScene();
  63838. if (!scene) {
  63839. return this;
  63840. }
  63841. var textureSize = this.getSize();
  63842. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  63843. // Base texture
  63844. newTexture.hasAlpha = this.hasAlpha;
  63845. newTexture.level = this.level;
  63846. // Refraction Texture
  63847. newTexture.refractionPlane = this.refractionPlane.clone();
  63848. if (this.renderList) {
  63849. newTexture.renderList = this.renderList.slice(0);
  63850. }
  63851. newTexture.depth = this.depth;
  63852. return newTexture;
  63853. };
  63854. RefractionTexture.prototype.serialize = function () {
  63855. if (!this.name) {
  63856. return null;
  63857. }
  63858. var serializationObject = _super.prototype.serialize.call(this);
  63859. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  63860. serializationObject.depth = this.depth;
  63861. return serializationObject;
  63862. };
  63863. return RefractionTexture;
  63864. }(BABYLON.RenderTargetTexture));
  63865. BABYLON.RefractionTexture = RefractionTexture;
  63866. })(BABYLON || (BABYLON = {}));
  63867. //# sourceMappingURL=babylon.refractionTexture.js.map
  63868. var BABYLON;
  63869. (function (BABYLON) {
  63870. /**
  63871. * A class extending {BABYLON.Texture} allowing drawing on a texture
  63872. * @see http://doc.babylonjs.com/how_to/dynamictexture
  63873. */
  63874. var DynamicTexture = /** @class */ (function (_super) {
  63875. __extends(DynamicTexture, _super);
  63876. /**
  63877. * Creates a {BABYLON.DynamicTexture}
  63878. * @param name defines the name of the texture
  63879. * @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
  63880. * @param scene defines the scene where you want the texture
  63881. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  63882. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  63883. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  63884. */
  63885. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  63886. if (scene === void 0) { scene = null; }
  63887. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63888. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63889. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  63890. _this.name = name;
  63891. _this._engine = _this.getScene().getEngine();
  63892. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63893. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63894. _this._generateMipMaps = generateMipMaps;
  63895. if (options.getContext) {
  63896. _this._canvas = options;
  63897. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  63898. }
  63899. else {
  63900. _this._canvas = document.createElement("canvas");
  63901. if (options.width || options.width === 0) {
  63902. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  63903. }
  63904. else {
  63905. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  63906. }
  63907. }
  63908. var textureSize = _this.getSize();
  63909. _this._canvas.width = textureSize.width;
  63910. _this._canvas.height = textureSize.height;
  63911. _this._context = _this._canvas.getContext("2d");
  63912. return _this;
  63913. }
  63914. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  63915. /**
  63916. * Gets the current state of canRescale
  63917. */
  63918. get: function () {
  63919. return true;
  63920. },
  63921. enumerable: true,
  63922. configurable: true
  63923. });
  63924. DynamicTexture.prototype._recreate = function (textureSize) {
  63925. this._canvas.width = textureSize.width;
  63926. this._canvas.height = textureSize.height;
  63927. this.releaseInternalTexture();
  63928. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  63929. };
  63930. /**
  63931. * Scales the texture
  63932. * @param ratio the scale factor to apply to both width and height
  63933. */
  63934. DynamicTexture.prototype.scale = function (ratio) {
  63935. var textureSize = this.getSize();
  63936. textureSize.width *= ratio;
  63937. textureSize.height *= ratio;
  63938. this._recreate(textureSize);
  63939. };
  63940. /**
  63941. * Resizes the texture
  63942. * @param width the new width
  63943. * @param height the new height
  63944. */
  63945. DynamicTexture.prototype.scaleTo = function (width, height) {
  63946. var textureSize = this.getSize();
  63947. textureSize.width = width;
  63948. textureSize.height = height;
  63949. this._recreate(textureSize);
  63950. };
  63951. /**
  63952. * Gets the context of the canvas used by the texture
  63953. * @returns the canvas context of the dynamic texture
  63954. */
  63955. DynamicTexture.prototype.getContext = function () {
  63956. return this._context;
  63957. };
  63958. /**
  63959. * Clears the texture
  63960. */
  63961. DynamicTexture.prototype.clear = function () {
  63962. var size = this.getSize();
  63963. this._context.fillRect(0, 0, size.width, size.height);
  63964. };
  63965. /**
  63966. * Updates the texture
  63967. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  63968. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  63969. */
  63970. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  63971. if (premulAlpha === void 0) { premulAlpha = false; }
  63972. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  63973. };
  63974. /**
  63975. * Draws text onto the texture
  63976. * @param text defines the text to be drawn
  63977. * @param x defines the placement of the text from the left
  63978. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  63979. * @param font defines the font to be used with font-style, font-size, font-name
  63980. * @param color defines the color used for the text
  63981. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  63982. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  63983. * @param update defines whether texture is immediately update (default is true)
  63984. */
  63985. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  63986. if (update === void 0) { update = true; }
  63987. var size = this.getSize();
  63988. if (clearColor) {
  63989. this._context.fillStyle = clearColor;
  63990. this._context.fillRect(0, 0, size.width, size.height);
  63991. }
  63992. this._context.font = font;
  63993. if (x === null || x === undefined) {
  63994. var textSize = this._context.measureText(text);
  63995. x = (size.width - textSize.width) / 2;
  63996. }
  63997. if (y === null || y === undefined) {
  63998. var fontSize = parseInt((font.replace(/\D/g, '')));
  63999. y = (size.height / 2) + (fontSize / 3.65);
  64000. }
  64001. this._context.fillStyle = color;
  64002. this._context.fillText(text, x, y);
  64003. if (update) {
  64004. this.update(invertY);
  64005. }
  64006. };
  64007. /**
  64008. * Clones the texture
  64009. * @returns the clone of the texture.
  64010. */
  64011. DynamicTexture.prototype.clone = function () {
  64012. var scene = this.getScene();
  64013. if (!scene) {
  64014. return this;
  64015. }
  64016. var textureSize = this.getSize();
  64017. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64018. // Base texture
  64019. newTexture.hasAlpha = this.hasAlpha;
  64020. newTexture.level = this.level;
  64021. // Dynamic Texture
  64022. newTexture.wrapU = this.wrapU;
  64023. newTexture.wrapV = this.wrapV;
  64024. return newTexture;
  64025. };
  64026. /** @hidden */
  64027. DynamicTexture.prototype._rebuild = function () {
  64028. this.update();
  64029. };
  64030. return DynamicTexture;
  64031. }(BABYLON.Texture));
  64032. BABYLON.DynamicTexture = DynamicTexture;
  64033. })(BABYLON || (BABYLON = {}));
  64034. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64035. var BABYLON;
  64036. (function (BABYLON) {
  64037. var VideoTexture = /** @class */ (function (_super) {
  64038. __extends(VideoTexture, _super);
  64039. /**
  64040. * Creates a video texture.
  64041. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64042. * @param {string | null} name optional name, will detect from video source, if not defined
  64043. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64044. * @param {BABYLON.Scene} scene is obviously the current scene.
  64045. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64046. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64047. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64048. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64049. */
  64050. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64051. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64052. if (invertY === void 0) { invertY = false; }
  64053. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64054. if (settings === void 0) { settings = {
  64055. autoPlay: true,
  64056. loop: true,
  64057. autoUpdateTexture: true,
  64058. }; }
  64059. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64060. _this._onUserActionRequestedObservable = null;
  64061. _this._stillImageCaptured = false;
  64062. _this._createInternalTexture = function () {
  64063. if (_this._texture != null) {
  64064. return;
  64065. }
  64066. if (!_this._engine.needPOTTextures ||
  64067. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64068. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64069. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64070. }
  64071. else {
  64072. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64073. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64074. _this._generateMipMaps = false;
  64075. }
  64076. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64077. if (!_this.video.autoplay) {
  64078. var oldHandler_1 = _this.video.onplaying;
  64079. var error_1 = false;
  64080. _this.video.onplaying = function () {
  64081. _this.video.onplaying = oldHandler_1;
  64082. _this._texture.isReady = true;
  64083. _this._updateInternalTexture();
  64084. if (!error_1) {
  64085. _this.video.pause();
  64086. }
  64087. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64088. _this.onLoadObservable.notifyObservers(_this);
  64089. }
  64090. };
  64091. var playing = _this.video.play();
  64092. if (playing) {
  64093. playing.then(function () {
  64094. // Everything is good.
  64095. })
  64096. .catch(function () {
  64097. error_1 = true;
  64098. // On Chrome for instance, new policies might prevent playing without user interaction.
  64099. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  64100. _this._onUserActionRequestedObservable.notifyObservers(_this);
  64101. }
  64102. });
  64103. }
  64104. else {
  64105. _this.video.onplaying = oldHandler_1;
  64106. _this._texture.isReady = true;
  64107. _this._updateInternalTexture();
  64108. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64109. _this.onLoadObservable.notifyObservers(_this);
  64110. }
  64111. }
  64112. }
  64113. else {
  64114. _this._texture.isReady = true;
  64115. _this._updateInternalTexture();
  64116. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64117. _this.onLoadObservable.notifyObservers(_this);
  64118. }
  64119. }
  64120. };
  64121. _this.reset = function () {
  64122. if (_this._texture == null) {
  64123. return;
  64124. }
  64125. _this._texture.dispose();
  64126. _this._texture = null;
  64127. };
  64128. _this._updateInternalTexture = function (e) {
  64129. if (_this._texture == null || !_this._texture.isReady) {
  64130. return;
  64131. }
  64132. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64133. return;
  64134. }
  64135. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64136. };
  64137. _this._engine = _this.getScene().getEngine();
  64138. _this._generateMipMaps = generateMipMaps;
  64139. _this._samplingMode = samplingMode;
  64140. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64141. _this.name = name || _this._getName(src);
  64142. _this.video = _this._getVideo(src);
  64143. if (settings.poster) {
  64144. _this.video.poster = settings.poster;
  64145. }
  64146. if (settings.autoPlay !== undefined) {
  64147. _this.video.autoplay = settings.autoPlay;
  64148. }
  64149. if (settings.loop !== undefined) {
  64150. _this.video.loop = settings.loop;
  64151. }
  64152. _this.video.setAttribute("playsinline", "");
  64153. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64154. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64155. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64156. _this.video.addEventListener("emptied", _this.reset);
  64157. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64158. _this._createInternalTexture();
  64159. }
  64160. return _this;
  64161. }
  64162. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  64163. get: function () {
  64164. if (!this._onUserActionRequestedObservable) {
  64165. this._onUserActionRequestedObservable = new BABYLON.Observable();
  64166. }
  64167. return this._onUserActionRequestedObservable;
  64168. },
  64169. enumerable: true,
  64170. configurable: true
  64171. });
  64172. VideoTexture.prototype._getName = function (src) {
  64173. if (src instanceof HTMLVideoElement) {
  64174. return src.currentSrc;
  64175. }
  64176. if (typeof src === "object") {
  64177. return src.toString();
  64178. }
  64179. return src;
  64180. };
  64181. ;
  64182. VideoTexture.prototype._getVideo = function (src) {
  64183. if (src instanceof HTMLVideoElement) {
  64184. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64185. return src;
  64186. }
  64187. var video = document.createElement("video");
  64188. if (typeof src === "string") {
  64189. BABYLON.Tools.SetCorsBehavior(src, video);
  64190. video.src = src;
  64191. }
  64192. else {
  64193. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64194. src.forEach(function (url) {
  64195. var source = document.createElement("source");
  64196. source.src = url;
  64197. video.appendChild(source);
  64198. });
  64199. }
  64200. return video;
  64201. };
  64202. ;
  64203. /**
  64204. * Internal method to initiate `update`.
  64205. */
  64206. VideoTexture.prototype._rebuild = function () {
  64207. this.update();
  64208. };
  64209. /**
  64210. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64211. */
  64212. VideoTexture.prototype.update = function () {
  64213. if (!this.autoUpdateTexture) {
  64214. // Expecting user to call `updateTexture` manually
  64215. return;
  64216. }
  64217. this.updateTexture(true);
  64218. };
  64219. /**
  64220. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64221. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64222. */
  64223. VideoTexture.prototype.updateTexture = function (isVisible) {
  64224. if (!isVisible) {
  64225. return;
  64226. }
  64227. if (this.video.paused && this._stillImageCaptured) {
  64228. return;
  64229. }
  64230. this._stillImageCaptured = true;
  64231. this._updateInternalTexture();
  64232. };
  64233. /**
  64234. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64235. * @param url New url.
  64236. */
  64237. VideoTexture.prototype.updateURL = function (url) {
  64238. this.video.src = url;
  64239. };
  64240. VideoTexture.prototype.dispose = function () {
  64241. _super.prototype.dispose.call(this);
  64242. if (this._onUserActionRequestedObservable) {
  64243. this._onUserActionRequestedObservable.clear();
  64244. this._onUserActionRequestedObservable = null;
  64245. }
  64246. this.video.removeEventListener("canplay", this._createInternalTexture);
  64247. this.video.removeEventListener("paused", this._updateInternalTexture);
  64248. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64249. this.video.removeEventListener("emptied", this.reset);
  64250. this.video.pause();
  64251. };
  64252. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64253. var video = document.createElement("video");
  64254. var constraintsDeviceId;
  64255. if (constraints && constraints.deviceId) {
  64256. constraintsDeviceId = {
  64257. exact: constraints.deviceId,
  64258. };
  64259. }
  64260. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64261. if (navigator.mediaDevices) {
  64262. navigator.mediaDevices.getUserMedia({ video: constraints })
  64263. .then(function (stream) {
  64264. if (video.mozSrcObject !== undefined) {
  64265. // hack for Firefox < 19
  64266. video.mozSrcObject = stream;
  64267. }
  64268. else {
  64269. video.srcObject = stream;
  64270. }
  64271. var onPlaying = function () {
  64272. if (onReady) {
  64273. onReady(new VideoTexture("video", video, scene, true, true));
  64274. }
  64275. video.removeEventListener("playing", onPlaying);
  64276. };
  64277. video.addEventListener("playing", onPlaying);
  64278. video.play();
  64279. })
  64280. .catch(function (err) {
  64281. BABYLON.Tools.Error(err.name);
  64282. });
  64283. }
  64284. else {
  64285. navigator.getUserMedia =
  64286. navigator.getUserMedia ||
  64287. navigator.webkitGetUserMedia ||
  64288. navigator.mozGetUserMedia ||
  64289. navigator.msGetUserMedia;
  64290. if (navigator.getUserMedia) {
  64291. navigator.getUserMedia({
  64292. video: {
  64293. deviceId: constraintsDeviceId,
  64294. width: {
  64295. min: (constraints && constraints.minWidth) || 256,
  64296. max: (constraints && constraints.maxWidth) || 640,
  64297. },
  64298. height: {
  64299. min: (constraints && constraints.minHeight) || 256,
  64300. max: (constraints && constraints.maxHeight) || 480,
  64301. },
  64302. },
  64303. }, function (stream) {
  64304. if (video.mozSrcObject !== undefined) {
  64305. // hack for Firefox < 19
  64306. video.mozSrcObject = stream;
  64307. }
  64308. else {
  64309. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64310. }
  64311. video.play();
  64312. if (onReady) {
  64313. onReady(new VideoTexture("video", video, scene, true, true));
  64314. }
  64315. }, function (e) {
  64316. BABYLON.Tools.Error(e.name);
  64317. });
  64318. }
  64319. }
  64320. };
  64321. return VideoTexture;
  64322. }(BABYLON.Texture));
  64323. BABYLON.VideoTexture = VideoTexture;
  64324. })(BABYLON || (BABYLON = {}));
  64325. //# sourceMappingURL=babylon.videoTexture.js.map
  64326. var BABYLON;
  64327. (function (BABYLON) {
  64328. var RawTexture = /** @class */ (function (_super) {
  64329. __extends(RawTexture, _super);
  64330. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64331. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64332. if (invertY === void 0) { invertY = false; }
  64333. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64334. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64335. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64336. _this.format = format;
  64337. _this._engine = scene.getEngine();
  64338. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64339. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64340. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64341. return _this;
  64342. }
  64343. RawTexture.prototype.update = function (data) {
  64344. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64345. };
  64346. // Statics
  64347. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64348. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64349. if (invertY === void 0) { invertY = false; }
  64350. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64351. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64352. };
  64353. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64354. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64355. if (invertY === void 0) { invertY = false; }
  64356. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64357. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64358. };
  64359. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64360. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64361. if (invertY === void 0) { invertY = false; }
  64362. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64363. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64364. };
  64365. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64366. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64367. if (invertY === void 0) { invertY = false; }
  64368. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64369. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64370. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64371. };
  64372. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64373. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64374. if (invertY === void 0) { invertY = false; }
  64375. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64376. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64377. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64378. };
  64379. return RawTexture;
  64380. }(BABYLON.Texture));
  64381. BABYLON.RawTexture = RawTexture;
  64382. })(BABYLON || (BABYLON = {}));
  64383. //# sourceMappingURL=babylon.rawTexture.js.map
  64384. var BABYLON;
  64385. (function (BABYLON) {
  64386. /**
  64387. * Class used to store 3D textures containing user data
  64388. */
  64389. var RawTexture3D = /** @class */ (function (_super) {
  64390. __extends(RawTexture3D, _super);
  64391. /**
  64392. * Create a new RawTexture3D
  64393. * @param data defines the data of the texture
  64394. * @param width defines the width of the texture
  64395. * @param height defines the height of the texture
  64396. * @param depth defines the depth of the texture
  64397. * @param format defines the texture format to use
  64398. * @param scene defines the hosting scene
  64399. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64400. * @param invertY defines if texture must be stored with Y axis inverted
  64401. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64402. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  64403. */
  64404. function RawTexture3D(data, width, height, depth,
  64405. /** Gets or sets the texture format to use */
  64406. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  64407. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64408. if (invertY === void 0) { invertY = false; }
  64409. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64410. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64411. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64412. _this.format = format;
  64413. _this._engine = scene.getEngine();
  64414. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  64415. _this.is3D = true;
  64416. return _this;
  64417. }
  64418. /**
  64419. * Update the texture with new data
  64420. * @param data defines the data to store in the texture
  64421. */
  64422. RawTexture3D.prototype.update = function (data) {
  64423. if (!this._texture) {
  64424. return;
  64425. }
  64426. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64427. };
  64428. return RawTexture3D;
  64429. }(BABYLON.Texture));
  64430. BABYLON.RawTexture3D = RawTexture3D;
  64431. })(BABYLON || (BABYLON = {}));
  64432. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64433. var BABYLON;
  64434. (function (BABYLON) {
  64435. /**
  64436. * PostProcessManager is used to manage one or more post processes or post process pipelines
  64437. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64438. */
  64439. var PostProcessManager = /** @class */ (function () {
  64440. /**
  64441. * Creates a new instance PostProcess
  64442. * @param scene The scene that the post process is associated with.
  64443. */
  64444. function PostProcessManager(scene) {
  64445. this._vertexBuffers = {};
  64446. this._scene = scene;
  64447. }
  64448. PostProcessManager.prototype._prepareBuffers = function () {
  64449. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  64450. return;
  64451. }
  64452. // VBO
  64453. var vertices = [];
  64454. vertices.push(1, 1);
  64455. vertices.push(-1, 1);
  64456. vertices.push(-1, -1);
  64457. vertices.push(1, -1);
  64458. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64459. this._buildIndexBuffer();
  64460. };
  64461. PostProcessManager.prototype._buildIndexBuffer = function () {
  64462. // Indices
  64463. var indices = [];
  64464. indices.push(0);
  64465. indices.push(1);
  64466. indices.push(2);
  64467. indices.push(0);
  64468. indices.push(2);
  64469. indices.push(3);
  64470. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  64471. };
  64472. /**
  64473. * Rebuilds the vertex buffers of the manager.
  64474. */
  64475. PostProcessManager.prototype._rebuild = function () {
  64476. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64477. if (!vb) {
  64478. return;
  64479. }
  64480. vb._rebuild();
  64481. this._buildIndexBuffer();
  64482. };
  64483. // Methods
  64484. /**
  64485. * Prepares a frame to be run through a post process.
  64486. * @param sourceTexture The input texture to the post procesess. (default: null)
  64487. * @param postProcesses An array of post processes to be run. (default: null)
  64488. * @returns True if the post processes were able to be run.
  64489. */
  64490. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  64491. if (sourceTexture === void 0) { sourceTexture = null; }
  64492. if (postProcesses === void 0) { postProcesses = null; }
  64493. var camera = this._scene.activeCamera;
  64494. if (!camera) {
  64495. return false;
  64496. }
  64497. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  64498. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  64499. return false;
  64500. }
  64501. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  64502. return true;
  64503. };
  64504. /**
  64505. * Manually render a set of post processes to a texture.
  64506. * @param postProcesses An array of post processes to be run.
  64507. * @param targetTexture The target texture to render to.
  64508. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  64509. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  64510. * @param lodLevel defines which lod of the texture to render to
  64511. */
  64512. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  64513. if (targetTexture === void 0) { targetTexture = null; }
  64514. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  64515. if (faceIndex === void 0) { faceIndex = 0; }
  64516. if (lodLevel === void 0) { lodLevel = 0; }
  64517. var engine = this._scene.getEngine();
  64518. for (var index = 0; index < postProcesses.length; index++) {
  64519. if (index < postProcesses.length - 1) {
  64520. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  64521. }
  64522. else {
  64523. if (targetTexture) {
  64524. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  64525. }
  64526. else {
  64527. engine.restoreDefaultFramebuffer();
  64528. }
  64529. }
  64530. var pp = postProcesses[index];
  64531. var effect = pp.apply();
  64532. if (effect) {
  64533. pp.onBeforeRenderObservable.notifyObservers(effect);
  64534. // VBOs
  64535. this._prepareBuffers();
  64536. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  64537. // Draw order
  64538. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64539. pp.onAfterRenderObservable.notifyObservers(effect);
  64540. }
  64541. }
  64542. // Restore depth buffer
  64543. engine.setDepthBuffer(true);
  64544. engine.setDepthWrite(true);
  64545. };
  64546. /**
  64547. * Finalize the result of the output of the postprocesses.
  64548. * @param doNotPresent If true the result will not be displayed to the screen.
  64549. * @param targetTexture The target texture to render to.
  64550. * @param faceIndex The index of the face to bind the target texture to.
  64551. * @param postProcesses The array of post processes to render.
  64552. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  64553. */
  64554. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  64555. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  64556. var camera = this._scene.activeCamera;
  64557. if (!camera) {
  64558. return;
  64559. }
  64560. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  64561. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  64562. return;
  64563. }
  64564. var engine = this._scene.getEngine();
  64565. for (var index = 0, len = postProcesses.length; index < len; index++) {
  64566. var pp = postProcesses[index];
  64567. if (index < len - 1) {
  64568. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  64569. }
  64570. else {
  64571. if (targetTexture) {
  64572. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  64573. pp._outputTexture = targetTexture;
  64574. }
  64575. else {
  64576. engine.restoreDefaultFramebuffer();
  64577. pp._outputTexture = null;
  64578. }
  64579. }
  64580. if (doNotPresent) {
  64581. break;
  64582. }
  64583. var effect = pp.apply();
  64584. if (effect) {
  64585. pp.onBeforeRenderObservable.notifyObservers(effect);
  64586. // VBOs
  64587. this._prepareBuffers();
  64588. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  64589. // Draw order
  64590. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64591. pp.onAfterRenderObservable.notifyObservers(effect);
  64592. }
  64593. }
  64594. // Restore states
  64595. engine.setDepthBuffer(true);
  64596. engine.setDepthWrite(true);
  64597. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  64598. };
  64599. /**
  64600. * Disposes of the post process manager.
  64601. */
  64602. PostProcessManager.prototype.dispose = function () {
  64603. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64604. if (buffer) {
  64605. buffer.dispose();
  64606. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64607. }
  64608. if (this._indexBuffer) {
  64609. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  64610. this._indexBuffer = null;
  64611. }
  64612. };
  64613. return PostProcessManager;
  64614. }());
  64615. BABYLON.PostProcessManager = PostProcessManager;
  64616. })(BABYLON || (BABYLON = {}));
  64617. //# sourceMappingURL=babylon.postProcessManager.js.map
  64618. var BABYLON;
  64619. (function (BABYLON) {
  64620. /**
  64621. * PostProcess can be used to apply a shader to a texture after it has been rendered
  64622. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64623. */
  64624. var PostProcess = /** @class */ (function () {
  64625. /**
  64626. * Creates a new instance PostProcess
  64627. * @param name The name of the PostProcess.
  64628. * @param fragmentUrl The url of the fragment shader to be used.
  64629. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  64630. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  64631. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  64632. * @param camera The camera to apply the render pass to.
  64633. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64634. * @param engine The engine which the post process will be applied. (default: current engine)
  64635. * @param reusable If the post process can be reused on the same frame. (default: false)
  64636. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  64637. * @param textureType Type of textures used when performing the post process. (default: 0)
  64638. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  64639. * @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
  64640. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  64641. */
  64642. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  64643. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  64644. if (defines === void 0) { defines = null; }
  64645. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64646. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  64647. if (blockCompilation === void 0) { blockCompilation = false; }
  64648. this.name = name;
  64649. /**
  64650. * Width of the texture to apply the post process on
  64651. */
  64652. this.width = -1;
  64653. /**
  64654. * Height of the texture to apply the post process on
  64655. */
  64656. this.height = -1;
  64657. /**
  64658. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  64659. */
  64660. this._outputTexture = null;
  64661. /**
  64662. * If the buffer needs to be cleared before applying the post process. (default: true)
  64663. * Should be set to false if shader will overwrite all previous pixels.
  64664. */
  64665. this.autoClear = true;
  64666. /**
  64667. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  64668. */
  64669. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  64670. /**
  64671. * Animations to be used for the post processing
  64672. */
  64673. this.animations = new Array();
  64674. /**
  64675. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  64676. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  64677. */
  64678. this.enablePixelPerfectMode = false;
  64679. /**
  64680. * Force the postprocess to be applied without taking in account viewport
  64681. */
  64682. this.forceFullscreenViewport = true;
  64683. /**
  64684. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  64685. *
  64686. * | Value | Type | Description |
  64687. * | ----- | ----------------------------------- | ----------- |
  64688. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  64689. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  64690. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  64691. *
  64692. */
  64693. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  64694. /**
  64695. * Force textures to be a power of two (default: false)
  64696. */
  64697. this.alwaysForcePOT = false;
  64698. /**
  64699. * Number of sample textures (default: 1)
  64700. */
  64701. this.samples = 1;
  64702. /**
  64703. * Modify the scale of the post process to be the same as the viewport (default: false)
  64704. */
  64705. this.adaptScaleToCurrentViewport = false;
  64706. this._reusable = false;
  64707. /**
  64708. * Smart array of input and output textures for the post process.
  64709. */
  64710. this._textures = new BABYLON.SmartArray(2);
  64711. /**
  64712. * The index in _textures that corresponds to the output texture.
  64713. */
  64714. this._currentRenderTextureInd = 0;
  64715. this._scaleRatio = new BABYLON.Vector2(1, 1);
  64716. this._texelSize = BABYLON.Vector2.Zero();
  64717. // Events
  64718. /**
  64719. * An event triggered when the postprocess is activated.
  64720. */
  64721. this.onActivateObservable = new BABYLON.Observable();
  64722. /**
  64723. * An event triggered when the postprocess changes its size.
  64724. */
  64725. this.onSizeChangedObservable = new BABYLON.Observable();
  64726. /**
  64727. * An event triggered when the postprocess applies its effect.
  64728. */
  64729. this.onApplyObservable = new BABYLON.Observable();
  64730. /**
  64731. * An event triggered before rendering the postprocess
  64732. */
  64733. this.onBeforeRenderObservable = new BABYLON.Observable();
  64734. /**
  64735. * An event triggered after rendering the postprocess
  64736. */
  64737. this.onAfterRenderObservable = new BABYLON.Observable();
  64738. if (camera != null) {
  64739. this._camera = camera;
  64740. this._scene = camera.getScene();
  64741. camera.attachPostProcess(this);
  64742. this._engine = this._scene.getEngine();
  64743. this._scene.postProcesses.push(this);
  64744. }
  64745. else if (engine) {
  64746. this._engine = engine;
  64747. this._engine.postProcesses.push(this);
  64748. }
  64749. this._options = options;
  64750. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  64751. this._reusable = reusable || false;
  64752. this._textureType = textureType;
  64753. this._samplers = samplers || [];
  64754. this._samplers.push("textureSampler");
  64755. this._fragmentUrl = fragmentUrl;
  64756. this._vertexUrl = vertexUrl;
  64757. this._parameters = parameters || [];
  64758. this._parameters.push("scale");
  64759. this._indexParameters = indexParameters;
  64760. if (!blockCompilation) {
  64761. this.updateEffect(defines);
  64762. }
  64763. }
  64764. Object.defineProperty(PostProcess.prototype, "onActivate", {
  64765. /**
  64766. * A function that is added to the onActivateObservable
  64767. */
  64768. set: function (callback) {
  64769. if (this._onActivateObserver) {
  64770. this.onActivateObservable.remove(this._onActivateObserver);
  64771. }
  64772. if (callback) {
  64773. this._onActivateObserver = this.onActivateObservable.add(callback);
  64774. }
  64775. },
  64776. enumerable: true,
  64777. configurable: true
  64778. });
  64779. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  64780. /**
  64781. * A function that is added to the onSizeChangedObservable
  64782. */
  64783. set: function (callback) {
  64784. if (this._onSizeChangedObserver) {
  64785. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  64786. }
  64787. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  64788. },
  64789. enumerable: true,
  64790. configurable: true
  64791. });
  64792. Object.defineProperty(PostProcess.prototype, "onApply", {
  64793. /**
  64794. * A function that is added to the onApplyObservable
  64795. */
  64796. set: function (callback) {
  64797. if (this._onApplyObserver) {
  64798. this.onApplyObservable.remove(this._onApplyObserver);
  64799. }
  64800. this._onApplyObserver = this.onApplyObservable.add(callback);
  64801. },
  64802. enumerable: true,
  64803. configurable: true
  64804. });
  64805. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  64806. /**
  64807. * A function that is added to the onBeforeRenderObservable
  64808. */
  64809. set: function (callback) {
  64810. if (this._onBeforeRenderObserver) {
  64811. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  64812. }
  64813. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  64814. },
  64815. enumerable: true,
  64816. configurable: true
  64817. });
  64818. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  64819. /**
  64820. * A function that is added to the onAfterRenderObservable
  64821. */
  64822. set: function (callback) {
  64823. if (this._onAfterRenderObserver) {
  64824. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  64825. }
  64826. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  64827. },
  64828. enumerable: true,
  64829. configurable: true
  64830. });
  64831. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  64832. /**
  64833. * 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
  64834. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  64835. */
  64836. get: function () {
  64837. return this._textures.data[this._currentRenderTextureInd];
  64838. },
  64839. set: function (value) {
  64840. this._forcedOutputTexture = value;
  64841. },
  64842. enumerable: true,
  64843. configurable: true
  64844. });
  64845. /**
  64846. * Gets the camera which post process is applied to.
  64847. * @returns The camera the post process is applied to.
  64848. */
  64849. PostProcess.prototype.getCamera = function () {
  64850. return this._camera;
  64851. };
  64852. Object.defineProperty(PostProcess.prototype, "texelSize", {
  64853. /**
  64854. * Gets the texel size of the postprocess.
  64855. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  64856. */
  64857. get: function () {
  64858. if (this._shareOutputWithPostProcess) {
  64859. return this._shareOutputWithPostProcess.texelSize;
  64860. }
  64861. if (this._forcedOutputTexture) {
  64862. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  64863. }
  64864. return this._texelSize;
  64865. },
  64866. enumerable: true,
  64867. configurable: true
  64868. });
  64869. /**
  64870. * Gets the engine which this post process belongs to.
  64871. * @returns The engine the post process was enabled with.
  64872. */
  64873. PostProcess.prototype.getEngine = function () {
  64874. return this._engine;
  64875. };
  64876. /**
  64877. * The effect that is created when initializing the post process.
  64878. * @returns The created effect corrisponding the the postprocess.
  64879. */
  64880. PostProcess.prototype.getEffect = function () {
  64881. return this._effect;
  64882. };
  64883. /**
  64884. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  64885. * @param postProcess The post process to share the output with.
  64886. * @returns This post process.
  64887. */
  64888. PostProcess.prototype.shareOutputWith = function (postProcess) {
  64889. this._disposeTextures();
  64890. this._shareOutputWithPostProcess = postProcess;
  64891. return this;
  64892. };
  64893. /**
  64894. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  64895. * This should be called if the post process that shares output with this post process is disabled/disposed.
  64896. */
  64897. PostProcess.prototype.useOwnOutput = function () {
  64898. if (this._textures.length == 0) {
  64899. this._textures = new BABYLON.SmartArray(2);
  64900. }
  64901. this._shareOutputWithPostProcess = null;
  64902. };
  64903. /**
  64904. * Updates the effect with the current post process compile time values and recompiles the shader.
  64905. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  64906. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  64907. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  64908. * @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
  64909. * @param onCompiled Called when the shader has been compiled.
  64910. * @param onError Called if there is an error when compiling a shader.
  64911. */
  64912. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  64913. if (defines === void 0) { defines = null; }
  64914. if (uniforms === void 0) { uniforms = null; }
  64915. if (samplers === void 0) { samplers = null; }
  64916. 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);
  64917. };
  64918. /**
  64919. * The post process is reusable if it can be used multiple times within one frame.
  64920. * @returns If the post process is reusable
  64921. */
  64922. PostProcess.prototype.isReusable = function () {
  64923. return this._reusable;
  64924. };
  64925. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  64926. PostProcess.prototype.markTextureDirty = function () {
  64927. this.width = -1;
  64928. };
  64929. /**
  64930. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  64931. * 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.
  64932. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  64933. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  64934. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  64935. * @returns The target texture that was bound to be written to.
  64936. */
  64937. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  64938. var _this = this;
  64939. if (sourceTexture === void 0) { sourceTexture = null; }
  64940. camera = camera || this._camera;
  64941. var scene = camera.getScene();
  64942. var engine = scene.getEngine();
  64943. var maxSize = engine.getCaps().maxTextureSize;
  64944. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  64945. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  64946. // 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
  64947. var webVRCamera = camera.parent;
  64948. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  64949. requiredWidth /= 2;
  64950. }
  64951. var desiredWidth = (this._options.width || requiredWidth);
  64952. var desiredHeight = this._options.height || requiredHeight;
  64953. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  64954. if (this.adaptScaleToCurrentViewport) {
  64955. var currentViewport = engine.currentViewport;
  64956. if (currentViewport) {
  64957. desiredWidth *= currentViewport.width;
  64958. desiredHeight *= currentViewport.height;
  64959. }
  64960. }
  64961. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  64962. if (!this._options.width) {
  64963. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  64964. }
  64965. if (!this._options.height) {
  64966. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  64967. }
  64968. }
  64969. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  64970. if (this._textures.length > 0) {
  64971. for (var i = 0; i < this._textures.length; i++) {
  64972. this._engine._releaseTexture(this._textures.data[i]);
  64973. }
  64974. this._textures.reset();
  64975. }
  64976. this.width = desiredWidth;
  64977. this.height = desiredHeight;
  64978. var textureSize = { width: this.width, height: this.height };
  64979. var textureOptions = {
  64980. generateMipMaps: false,
  64981. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  64982. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  64983. samplingMode: this.renderTargetSamplingMode,
  64984. type: this._textureType
  64985. };
  64986. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  64987. if (this._reusable) {
  64988. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  64989. }
  64990. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  64991. this.onSizeChangedObservable.notifyObservers(this);
  64992. }
  64993. this._textures.forEach(function (texture) {
  64994. if (texture.samples !== _this.samples) {
  64995. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  64996. }
  64997. });
  64998. }
  64999. var target;
  65000. if (this._shareOutputWithPostProcess) {
  65001. target = this._shareOutputWithPostProcess.inputTexture;
  65002. }
  65003. else if (this._forcedOutputTexture) {
  65004. target = this._forcedOutputTexture;
  65005. this.width = this._forcedOutputTexture.width;
  65006. this.height = this._forcedOutputTexture.height;
  65007. }
  65008. else {
  65009. target = this.inputTexture;
  65010. }
  65011. // Bind the input of this post process to be used as the output of the previous post process.
  65012. if (this.enablePixelPerfectMode) {
  65013. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65014. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65015. }
  65016. else {
  65017. this._scaleRatio.copyFromFloats(1, 1);
  65018. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65019. }
  65020. this.onActivateObservable.notifyObservers(camera);
  65021. // Clear
  65022. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65023. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65024. }
  65025. if (this._reusable) {
  65026. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65027. }
  65028. return target;
  65029. };
  65030. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65031. /**
  65032. * If the post process is supported.
  65033. */
  65034. get: function () {
  65035. return this._effect.isSupported;
  65036. },
  65037. enumerable: true,
  65038. configurable: true
  65039. });
  65040. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65041. /**
  65042. * The aspect ratio of the output texture.
  65043. */
  65044. get: function () {
  65045. if (this._shareOutputWithPostProcess) {
  65046. return this._shareOutputWithPostProcess.aspectRatio;
  65047. }
  65048. if (this._forcedOutputTexture) {
  65049. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65050. }
  65051. return this.width / this.height;
  65052. },
  65053. enumerable: true,
  65054. configurable: true
  65055. });
  65056. /**
  65057. * Get a value indicating if the post-process is ready to be used
  65058. * @returns true if the post-process is ready (shader is compiled)
  65059. */
  65060. PostProcess.prototype.isReady = function () {
  65061. return this._effect && this._effect.isReady();
  65062. };
  65063. /**
  65064. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65065. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65066. */
  65067. PostProcess.prototype.apply = function () {
  65068. // Check
  65069. if (!this._effect || !this._effect.isReady())
  65070. return null;
  65071. // States
  65072. this._engine.enableEffect(this._effect);
  65073. this._engine.setState(false);
  65074. this._engine.setDepthBuffer(false);
  65075. this._engine.setDepthWrite(false);
  65076. // Alpha
  65077. this._engine.setAlphaMode(this.alphaMode);
  65078. if (this.alphaConstants) {
  65079. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65080. }
  65081. // Bind the output texture of the preivous post process as the input to this post process.
  65082. var source;
  65083. if (this._shareOutputWithPostProcess) {
  65084. source = this._shareOutputWithPostProcess.inputTexture;
  65085. }
  65086. else if (this._forcedOutputTexture) {
  65087. source = this._forcedOutputTexture;
  65088. }
  65089. else {
  65090. source = this.inputTexture;
  65091. }
  65092. this._effect._bindTexture("textureSampler", source);
  65093. // Parameters
  65094. this._effect.setVector2("scale", this._scaleRatio);
  65095. this.onApplyObservable.notifyObservers(this._effect);
  65096. return this._effect;
  65097. };
  65098. PostProcess.prototype._disposeTextures = function () {
  65099. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65100. return;
  65101. }
  65102. if (this._textures.length > 0) {
  65103. for (var i = 0; i < this._textures.length; i++) {
  65104. this._engine._releaseTexture(this._textures.data[i]);
  65105. }
  65106. }
  65107. this._textures.dispose();
  65108. };
  65109. /**
  65110. * Disposes the post process.
  65111. * @param camera The camera to dispose the post process on.
  65112. */
  65113. PostProcess.prototype.dispose = function (camera) {
  65114. camera = camera || this._camera;
  65115. this._disposeTextures();
  65116. if (this._scene) {
  65117. var index_1 = this._scene.postProcesses.indexOf(this);
  65118. if (index_1 !== -1) {
  65119. this._scene.postProcesses.splice(index_1, 1);
  65120. }
  65121. }
  65122. else {
  65123. var index_2 = this._engine.postProcesses.indexOf(this);
  65124. if (index_2 !== -1) {
  65125. this._engine.postProcesses.splice(index_2, 1);
  65126. }
  65127. }
  65128. if (!camera) {
  65129. return;
  65130. }
  65131. camera.detachPostProcess(this);
  65132. var index = camera._postProcesses.indexOf(this);
  65133. if (index === 0 && camera._postProcesses.length > 0) {
  65134. var firstPostProcess = this._camera._getFirstPostProcess();
  65135. if (firstPostProcess) {
  65136. firstPostProcess.markTextureDirty();
  65137. }
  65138. }
  65139. this.onActivateObservable.clear();
  65140. this.onAfterRenderObservable.clear();
  65141. this.onApplyObservable.clear();
  65142. this.onBeforeRenderObservable.clear();
  65143. this.onSizeChangedObservable.clear();
  65144. };
  65145. return PostProcess;
  65146. }());
  65147. BABYLON.PostProcess = PostProcess;
  65148. })(BABYLON || (BABYLON = {}));
  65149. //# sourceMappingURL=babylon.postProcess.js.map
  65150. var BABYLON;
  65151. (function (BABYLON) {
  65152. var PassPostProcess = /** @class */ (function (_super) {
  65153. __extends(PassPostProcess, _super);
  65154. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65155. if (camera === void 0) { camera = null; }
  65156. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65157. if (blockCompilation === void 0) { blockCompilation = false; }
  65158. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65159. }
  65160. return PassPostProcess;
  65161. }(BABYLON.PostProcess));
  65162. BABYLON.PassPostProcess = PassPostProcess;
  65163. })(BABYLON || (BABYLON = {}));
  65164. //# sourceMappingURL=babylon.passPostProcess.js.map
  65165. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65166. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65167. s = arguments[i];
  65168. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65169. t[p] = s[p];
  65170. }
  65171. return t;
  65172. };
  65173. var BABYLON;
  65174. (function (BABYLON) {
  65175. /**
  65176. * Default implementation IShadowGenerator.
  65177. * This is the main object responsible of generating shadows in the framework.
  65178. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65179. */
  65180. var ShadowGenerator = /** @class */ (function () {
  65181. /**
  65182. * Creates a ShadowGenerator object.
  65183. * A ShadowGenerator is the required tool to use the shadows.
  65184. * Each light casting shadows needs to use its own ShadowGenerator.
  65185. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65186. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65187. * @param light The light object generating the shadows.
  65188. * @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.
  65189. */
  65190. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65191. this._bias = 0.00005;
  65192. this._normalBias = 0;
  65193. this._blurBoxOffset = 1;
  65194. this._blurScale = 2;
  65195. this._blurKernel = 1;
  65196. this._useKernelBlur = false;
  65197. this._filter = ShadowGenerator.FILTER_NONE;
  65198. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65199. this._contactHardeningLightSizeUVRatio = 0.1;
  65200. this._darkness = 0;
  65201. this._transparencyShadow = false;
  65202. /**
  65203. * Controls the extent to which the shadows fade out at the edge of the frustum
  65204. * Used only by directionals and spots
  65205. */
  65206. this.frustumEdgeFalloff = 0;
  65207. /**
  65208. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65209. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65210. * It might on the other hand introduce peter panning.
  65211. */
  65212. this.forceBackFacesOnly = false;
  65213. this._lightDirection = BABYLON.Vector3.Zero();
  65214. this._viewMatrix = BABYLON.Matrix.Zero();
  65215. this._projectionMatrix = BABYLON.Matrix.Zero();
  65216. this._transformMatrix = BABYLON.Matrix.Zero();
  65217. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65218. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65219. this._currentFaceIndex = 0;
  65220. this._currentFaceIndexCache = 0;
  65221. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65222. this._mapSize = mapSize;
  65223. this._light = light;
  65224. this._scene = light.getScene();
  65225. light._shadowGenerator = this;
  65226. // Texture type fallback from float to int if not supported.
  65227. var caps = this._scene.getEngine().getCaps();
  65228. if (!useFullFloatFirst) {
  65229. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65230. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65231. }
  65232. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65233. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65234. }
  65235. else {
  65236. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65237. }
  65238. }
  65239. else {
  65240. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65241. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65242. }
  65243. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65244. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65245. }
  65246. else {
  65247. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65248. }
  65249. }
  65250. this._initializeGenerator();
  65251. this._applyFilterValues();
  65252. }
  65253. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65254. /**
  65255. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65256. */
  65257. get: function () {
  65258. return this._bias;
  65259. },
  65260. /**
  65261. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65262. */
  65263. set: function (bias) {
  65264. this._bias = bias;
  65265. },
  65266. enumerable: true,
  65267. configurable: true
  65268. });
  65269. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65270. /**
  65271. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65272. */
  65273. get: function () {
  65274. return this._normalBias;
  65275. },
  65276. /**
  65277. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65278. */
  65279. set: function (normalBias) {
  65280. this._normalBias = normalBias;
  65281. },
  65282. enumerable: true,
  65283. configurable: true
  65284. });
  65285. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65286. /**
  65287. * Gets the blur box offset: offset applied during the blur pass.
  65288. * Only usefull if useKernelBlur = false
  65289. */
  65290. get: function () {
  65291. return this._blurBoxOffset;
  65292. },
  65293. /**
  65294. * Sets the blur box offset: offset applied during the blur pass.
  65295. * Only usefull if useKernelBlur = false
  65296. */
  65297. set: function (value) {
  65298. if (this._blurBoxOffset === value) {
  65299. return;
  65300. }
  65301. this._blurBoxOffset = value;
  65302. this._disposeBlurPostProcesses();
  65303. },
  65304. enumerable: true,
  65305. configurable: true
  65306. });
  65307. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65308. /**
  65309. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65310. * 2 means half of the size.
  65311. */
  65312. get: function () {
  65313. return this._blurScale;
  65314. },
  65315. /**
  65316. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65317. * 2 means half of the size.
  65318. */
  65319. set: function (value) {
  65320. if (this._blurScale === value) {
  65321. return;
  65322. }
  65323. this._blurScale = value;
  65324. this._disposeBlurPostProcesses();
  65325. },
  65326. enumerable: true,
  65327. configurable: true
  65328. });
  65329. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65330. /**
  65331. * Gets the blur kernel: kernel size of the blur pass.
  65332. * Only usefull if useKernelBlur = true
  65333. */
  65334. get: function () {
  65335. return this._blurKernel;
  65336. },
  65337. /**
  65338. * Sets the blur kernel: kernel size of the blur pass.
  65339. * Only usefull if useKernelBlur = true
  65340. */
  65341. set: function (value) {
  65342. if (this._blurKernel === value) {
  65343. return;
  65344. }
  65345. this._blurKernel = value;
  65346. this._disposeBlurPostProcesses();
  65347. },
  65348. enumerable: true,
  65349. configurable: true
  65350. });
  65351. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65352. /**
  65353. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65354. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65355. */
  65356. get: function () {
  65357. return this._useKernelBlur;
  65358. },
  65359. /**
  65360. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65361. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65362. */
  65363. set: function (value) {
  65364. if (this._useKernelBlur === value) {
  65365. return;
  65366. }
  65367. this._useKernelBlur = value;
  65368. this._disposeBlurPostProcesses();
  65369. },
  65370. enumerable: true,
  65371. configurable: true
  65372. });
  65373. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65374. /**
  65375. * Gets the depth scale used in ESM mode.
  65376. */
  65377. get: function () {
  65378. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65379. },
  65380. /**
  65381. * Sets the depth scale used in ESM mode.
  65382. * This can override the scale stored on the light.
  65383. */
  65384. set: function (value) {
  65385. this._depthScale = value;
  65386. },
  65387. enumerable: true,
  65388. configurable: true
  65389. });
  65390. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  65391. /**
  65392. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  65393. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65394. */
  65395. get: function () {
  65396. return this._filter;
  65397. },
  65398. /**
  65399. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  65400. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65401. */
  65402. set: function (value) {
  65403. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  65404. if (this._light.needCube()) {
  65405. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65406. this.useExponentialShadowMap = true;
  65407. return;
  65408. }
  65409. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65410. this.useCloseExponentialShadowMap = true;
  65411. return;
  65412. }
  65413. // PCF on cubemap would also be expensive
  65414. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65415. this.usePoissonSampling = true;
  65416. return;
  65417. }
  65418. }
  65419. // Weblg1 fallback for PCF.
  65420. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65421. if (this._scene.getEngine().webGLVersion === 1) {
  65422. this.usePoissonSampling = true;
  65423. return;
  65424. }
  65425. }
  65426. if (this._filter === value) {
  65427. return;
  65428. }
  65429. this._filter = value;
  65430. this._disposeBlurPostProcesses();
  65431. this._applyFilterValues();
  65432. this._light._markMeshesAsLightDirty();
  65433. },
  65434. enumerable: true,
  65435. configurable: true
  65436. });
  65437. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65438. /**
  65439. * Gets if the current filter is set to Poisson Sampling.
  65440. */
  65441. get: function () {
  65442. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65443. },
  65444. /**
  65445. * Sets the current filter to Poisson Sampling.
  65446. */
  65447. set: function (value) {
  65448. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65449. return;
  65450. }
  65451. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65452. },
  65453. enumerable: true,
  65454. configurable: true
  65455. });
  65456. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65457. /**
  65458. * Gets if the current filter is set to VSM.
  65459. * DEPRECATED. Should use useExponentialShadowMap instead.
  65460. */
  65461. get: function () {
  65462. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65463. return this.useExponentialShadowMap;
  65464. },
  65465. /**
  65466. * Sets the current filter is to VSM.
  65467. * DEPRECATED. Should use useExponentialShadowMap instead.
  65468. */
  65469. set: function (value) {
  65470. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65471. this.useExponentialShadowMap = value;
  65472. },
  65473. enumerable: true,
  65474. configurable: true
  65475. });
  65476. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65477. /**
  65478. * Gets if the current filter is set to blurred VSM.
  65479. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65480. */
  65481. get: function () {
  65482. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65483. return this.useBlurExponentialShadowMap;
  65484. },
  65485. /**
  65486. * Sets the current filter is to blurred VSM.
  65487. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65488. */
  65489. set: function (value) {
  65490. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65491. this.useBlurExponentialShadowMap = value;
  65492. },
  65493. enumerable: true,
  65494. configurable: true
  65495. });
  65496. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65497. /**
  65498. * Gets if the current filter is set to ESM.
  65499. */
  65500. get: function () {
  65501. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65502. },
  65503. /**
  65504. * Sets the current filter is to ESM.
  65505. */
  65506. set: function (value) {
  65507. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65508. return;
  65509. }
  65510. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65511. },
  65512. enumerable: true,
  65513. configurable: true
  65514. });
  65515. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65516. /**
  65517. * Gets if the current filter is set to filtered ESM.
  65518. */
  65519. get: function () {
  65520. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65521. },
  65522. /**
  65523. * Gets if the current filter is set to filtered ESM.
  65524. */
  65525. set: function (value) {
  65526. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65527. return;
  65528. }
  65529. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65530. },
  65531. enumerable: true,
  65532. configurable: true
  65533. });
  65534. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  65535. /**
  65536. * Gets if the current filter is set to "close ESM" (using the inverse of the
  65537. * exponential to prevent steep falloff artifacts).
  65538. */
  65539. get: function () {
  65540. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  65541. },
  65542. /**
  65543. * Sets the current filter to "close ESM" (using the inverse of the
  65544. * exponential to prevent steep falloff artifacts).
  65545. */
  65546. set: function (value) {
  65547. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  65548. return;
  65549. }
  65550. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65551. },
  65552. enumerable: true,
  65553. configurable: true
  65554. });
  65555. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  65556. /**
  65557. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  65558. * exponential to prevent steep falloff artifacts).
  65559. */
  65560. get: function () {
  65561. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  65562. },
  65563. /**
  65564. * Sets the current filter to filtered "close ESM" (using the inverse of the
  65565. * exponential to prevent steep falloff artifacts).
  65566. */
  65567. set: function (value) {
  65568. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65569. return;
  65570. }
  65571. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65572. },
  65573. enumerable: true,
  65574. configurable: true
  65575. });
  65576. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  65577. /**
  65578. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  65579. */
  65580. get: function () {
  65581. return this.filter === ShadowGenerator.FILTER_PCF;
  65582. },
  65583. /**
  65584. * Sets the current filter to "PCF" (percentage closer filtering).
  65585. */
  65586. set: function (value) {
  65587. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  65588. return;
  65589. }
  65590. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  65591. },
  65592. enumerable: true,
  65593. configurable: true
  65594. });
  65595. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  65596. /**
  65597. * Gets the PCF or PCSS Quality.
  65598. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65599. */
  65600. get: function () {
  65601. return this._filteringQuality;
  65602. },
  65603. /**
  65604. * Sets the PCF or PCSS Quality.
  65605. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65606. */
  65607. set: function (filteringQuality) {
  65608. this._filteringQuality = filteringQuality;
  65609. },
  65610. enumerable: true,
  65611. configurable: true
  65612. });
  65613. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  65614. /**
  65615. * Gets if the current filter is set to "PCSS" (contact hardening).
  65616. */
  65617. get: function () {
  65618. return this.filter === ShadowGenerator.FILTER_PCSS;
  65619. },
  65620. /**
  65621. * Sets the current filter to "PCSS" (contact hardening).
  65622. */
  65623. set: function (value) {
  65624. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  65625. return;
  65626. }
  65627. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  65628. },
  65629. enumerable: true,
  65630. configurable: true
  65631. });
  65632. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  65633. /**
  65634. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65635. * Using a ratio helps keeping shape stability independently of the map size.
  65636. *
  65637. * It does not account for the light projection as it was having too much
  65638. * instability during the light setup or during light position changes.
  65639. *
  65640. * Only valid if useContactHardeningShadow is true.
  65641. */
  65642. get: function () {
  65643. return this._contactHardeningLightSizeUVRatio;
  65644. },
  65645. /**
  65646. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65647. * Using a ratio helps keeping shape stability independently of the map size.
  65648. *
  65649. * It does not account for the light projection as it was having too much
  65650. * instability during the light setup or during light position changes.
  65651. *
  65652. * Only valid if useContactHardeningShadow is true.
  65653. */
  65654. set: function (contactHardeningLightSizeUVRatio) {
  65655. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  65656. },
  65657. enumerable: true,
  65658. configurable: true
  65659. });
  65660. /**
  65661. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  65662. * 0 means strongest and 1 would means no shadow.
  65663. * @returns the darkness.
  65664. */
  65665. ShadowGenerator.prototype.getDarkness = function () {
  65666. return this._darkness;
  65667. };
  65668. /**
  65669. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  65670. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  65671. * @returns the shadow generator allowing fluent coding.
  65672. */
  65673. ShadowGenerator.prototype.setDarkness = function (darkness) {
  65674. if (darkness >= 1.0)
  65675. this._darkness = 1.0;
  65676. else if (darkness <= 0.0)
  65677. this._darkness = 0.0;
  65678. else
  65679. this._darkness = darkness;
  65680. return this;
  65681. };
  65682. /**
  65683. * Sets the ability to have transparent shadow (boolean).
  65684. * @param transparent True if transparent else False
  65685. * @returns the shadow generator allowing fluent coding
  65686. */
  65687. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  65688. this._transparencyShadow = transparent;
  65689. return this;
  65690. };
  65691. /**
  65692. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  65693. * @returns The render target texture if present otherwise, null
  65694. */
  65695. ShadowGenerator.prototype.getShadowMap = function () {
  65696. return this._shadowMap;
  65697. };
  65698. /**
  65699. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  65700. * @returns The render target texture if the shadow map is present otherwise, null
  65701. */
  65702. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  65703. if (this._shadowMap2) {
  65704. return this._shadowMap2;
  65705. }
  65706. return this._shadowMap;
  65707. };
  65708. /**
  65709. * Helper function to add a mesh and its descendants to the list of shadow casters.
  65710. * @param mesh Mesh to add
  65711. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  65712. * @returns the Shadow Generator itself
  65713. */
  65714. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  65715. if (includeDescendants === void 0) { includeDescendants = true; }
  65716. if (!this._shadowMap) {
  65717. return this;
  65718. }
  65719. if (!this._shadowMap.renderList) {
  65720. this._shadowMap.renderList = [];
  65721. }
  65722. this._shadowMap.renderList.push(mesh);
  65723. if (includeDescendants) {
  65724. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  65725. }
  65726. return this;
  65727. var _a;
  65728. };
  65729. /**
  65730. * Helper function to remove a mesh and its descendants from the list of shadow casters
  65731. * @param mesh Mesh to remove
  65732. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  65733. * @returns the Shadow Generator itself
  65734. */
  65735. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  65736. if (includeDescendants === void 0) { includeDescendants = true; }
  65737. if (!this._shadowMap || !this._shadowMap.renderList) {
  65738. return this;
  65739. }
  65740. var index = this._shadowMap.renderList.indexOf(mesh);
  65741. if (index !== -1) {
  65742. this._shadowMap.renderList.splice(index, 1);
  65743. }
  65744. if (includeDescendants) {
  65745. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  65746. var child = _a[_i];
  65747. this.removeShadowCaster(child);
  65748. }
  65749. }
  65750. return this;
  65751. };
  65752. /**
  65753. * Returns the associated light object.
  65754. * @returns the light generating the shadow
  65755. */
  65756. ShadowGenerator.prototype.getLight = function () {
  65757. return this._light;
  65758. };
  65759. ShadowGenerator.prototype._initializeGenerator = function () {
  65760. this._light._markMeshesAsLightDirty();
  65761. this._initializeShadowMap();
  65762. };
  65763. ShadowGenerator.prototype._initializeShadowMap = function () {
  65764. var _this = this;
  65765. // Render target
  65766. var engine = this._scene.getEngine();
  65767. if (engine.webGLVersion > 1) {
  65768. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  65769. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  65770. }
  65771. else {
  65772. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  65773. }
  65774. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65775. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65776. this._shadowMap.anisotropicFilteringLevel = 1;
  65777. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65778. this._shadowMap.renderParticles = false;
  65779. this._shadowMap.ignoreCameraViewport = true;
  65780. // Record Face Index before render.
  65781. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  65782. _this._currentFaceIndex = faceIndex;
  65783. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65784. engine.setColorWrite(false);
  65785. }
  65786. });
  65787. // Custom render function.
  65788. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  65789. // Blur if required afer render.
  65790. this._shadowMap.onAfterUnbindObservable.add(function () {
  65791. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65792. engine.setColorWrite(true);
  65793. }
  65794. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  65795. return;
  65796. }
  65797. var shadowMap = _this.getShadowMapForRendering();
  65798. if (shadowMap) {
  65799. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  65800. }
  65801. });
  65802. // Clear according to the chosen filter.
  65803. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  65804. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  65805. this._shadowMap.onClearObservable.add(function (engine) {
  65806. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65807. engine.clear(clearOne, false, true, false);
  65808. }
  65809. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  65810. engine.clear(clearZero, true, true, false);
  65811. }
  65812. else {
  65813. engine.clear(clearOne, true, true, false);
  65814. }
  65815. });
  65816. };
  65817. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  65818. var _this = this;
  65819. var engine = this._scene.getEngine();
  65820. var targetSize = this._mapSize / this.blurScale;
  65821. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  65822. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  65823. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65824. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65825. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65826. }
  65827. if (this.useKernelBlur) {
  65828. 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);
  65829. this._kernelBlurXPostprocess.width = targetSize;
  65830. this._kernelBlurXPostprocess.height = targetSize;
  65831. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  65832. effect.setTexture("textureSampler", _this._shadowMap);
  65833. });
  65834. 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);
  65835. this._kernelBlurXPostprocess.autoClear = false;
  65836. this._kernelBlurYPostprocess.autoClear = false;
  65837. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65838. this._kernelBlurXPostprocess.packedFloat = true;
  65839. this._kernelBlurYPostprocess.packedFloat = true;
  65840. }
  65841. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  65842. }
  65843. else {
  65844. 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);
  65845. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  65846. effect.setFloat2("screenSize", targetSize, targetSize);
  65847. effect.setTexture("textureSampler", _this._shadowMap);
  65848. });
  65849. this._boxBlurPostprocess.autoClear = false;
  65850. this._blurPostProcesses = [this._boxBlurPostprocess];
  65851. }
  65852. };
  65853. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65854. var index;
  65855. var engine = this._scene.getEngine();
  65856. if (depthOnlySubMeshes.length) {
  65857. engine.setColorWrite(false);
  65858. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65859. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  65860. }
  65861. engine.setColorWrite(true);
  65862. }
  65863. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65864. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  65865. }
  65866. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65867. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  65868. }
  65869. if (this._transparencyShadow) {
  65870. for (index = 0; index < transparentSubMeshes.length; index++) {
  65871. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  65872. }
  65873. }
  65874. };
  65875. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  65876. var _this = this;
  65877. var mesh = subMesh.getRenderingMesh();
  65878. var scene = this._scene;
  65879. var engine = scene.getEngine();
  65880. var material = subMesh.getMaterial();
  65881. if (!material) {
  65882. return;
  65883. }
  65884. // Culling
  65885. engine.setState(material.backFaceCulling);
  65886. // Managing instances
  65887. var batch = mesh._getInstancesRenderList(subMesh._id);
  65888. if (batch.mustReturn) {
  65889. return;
  65890. }
  65891. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  65892. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  65893. engine.enableEffect(this._effect);
  65894. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  65895. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  65896. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  65897. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  65898. this._effect.setVector3("lightData", this._cachedDirection);
  65899. }
  65900. else {
  65901. this._effect.setVector3("lightData", this._cachedPosition);
  65902. }
  65903. if (scene.activeCamera) {
  65904. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  65905. }
  65906. // Alpha test
  65907. if (material && material.needAlphaTesting()) {
  65908. var alphaTexture = material.getAlphaTestTexture();
  65909. if (alphaTexture) {
  65910. this._effect.setTexture("diffuseSampler", alphaTexture);
  65911. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  65912. }
  65913. }
  65914. // Bones
  65915. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65916. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  65917. }
  65918. // Morph targets
  65919. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  65920. if (this.forceBackFacesOnly) {
  65921. engine.setState(true, 0, false, true);
  65922. }
  65923. // Draw
  65924. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  65925. if (this.forceBackFacesOnly) {
  65926. engine.setState(true, 0, false, false);
  65927. }
  65928. }
  65929. else {
  65930. // Need to reset refresh rate of the shadowMap
  65931. if (this._shadowMap) {
  65932. this._shadowMap.resetRefreshCounter();
  65933. }
  65934. }
  65935. };
  65936. ShadowGenerator.prototype._applyFilterValues = function () {
  65937. if (!this._shadowMap) {
  65938. return;
  65939. }
  65940. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  65941. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  65942. }
  65943. else {
  65944. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65945. }
  65946. };
  65947. /**
  65948. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  65949. * @param onCompiled Callback triggered at the and of the effects compilation
  65950. * @param options Sets of optional options forcing the compilation with different modes
  65951. */
  65952. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  65953. var _this = this;
  65954. var localOptions = __assign({ useInstances: false }, options);
  65955. var shadowMap = this.getShadowMap();
  65956. if (!shadowMap) {
  65957. if (onCompiled) {
  65958. onCompiled(this);
  65959. }
  65960. return;
  65961. }
  65962. var renderList = shadowMap.renderList;
  65963. if (!renderList) {
  65964. if (onCompiled) {
  65965. onCompiled(this);
  65966. }
  65967. return;
  65968. }
  65969. var subMeshes = new Array();
  65970. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  65971. var mesh = renderList_1[_i];
  65972. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  65973. }
  65974. if (subMeshes.length === 0) {
  65975. if (onCompiled) {
  65976. onCompiled(this);
  65977. }
  65978. return;
  65979. }
  65980. var currentIndex = 0;
  65981. var checkReady = function () {
  65982. if (!_this._scene || !_this._scene.getEngine()) {
  65983. return;
  65984. }
  65985. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  65986. currentIndex++;
  65987. if (currentIndex >= subMeshes.length) {
  65988. if (onCompiled) {
  65989. onCompiled(_this);
  65990. }
  65991. return;
  65992. }
  65993. }
  65994. setTimeout(checkReady, 16);
  65995. };
  65996. checkReady();
  65997. };
  65998. /**
  65999. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66000. * @param options Sets of optional options forcing the compilation with different modes
  66001. * @returns A promise that resolves when the compilation completes
  66002. */
  66003. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66004. var _this = this;
  66005. return new Promise(function (resolve) {
  66006. _this.forceCompilation(function () {
  66007. resolve();
  66008. }, options);
  66009. });
  66010. };
  66011. /**
  66012. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66013. * @param subMesh The submesh we want to render in the shadow map
  66014. * @param useInstances Defines wether will draw in the map using instances
  66015. * @returns true if ready otherwise, false
  66016. */
  66017. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66018. var defines = [];
  66019. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66020. defines.push("#define FLOAT");
  66021. }
  66022. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66023. defines.push("#define ESM");
  66024. }
  66025. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66026. defines.push("#define DEPTHTEXTURE");
  66027. }
  66028. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66029. var mesh = subMesh.getMesh();
  66030. var material = subMesh.getMaterial();
  66031. // Normal bias.
  66032. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66033. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66034. defines.push("#define NORMAL");
  66035. if (mesh.nonUniformScaling) {
  66036. defines.push("#define NONUNIFORMSCALING");
  66037. }
  66038. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66039. defines.push("#define DIRECTIONINLIGHTDATA");
  66040. }
  66041. }
  66042. // Alpha test
  66043. if (material && material.needAlphaTesting()) {
  66044. var alphaTexture = material.getAlphaTestTexture();
  66045. if (alphaTexture) {
  66046. defines.push("#define ALPHATEST");
  66047. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66048. attribs.push(BABYLON.VertexBuffer.UVKind);
  66049. defines.push("#define UV1");
  66050. }
  66051. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66052. if (alphaTexture.coordinatesIndex === 1) {
  66053. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66054. defines.push("#define UV2");
  66055. }
  66056. }
  66057. }
  66058. }
  66059. // Bones
  66060. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66061. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66062. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66063. if (mesh.numBoneInfluencers > 4) {
  66064. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66065. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66066. }
  66067. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66068. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66069. }
  66070. else {
  66071. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66072. }
  66073. // Morph targets
  66074. var manager = mesh.morphTargetManager;
  66075. var morphInfluencers = 0;
  66076. if (manager) {
  66077. if (manager.numInfluencers > 0) {
  66078. defines.push("#define MORPHTARGETS");
  66079. morphInfluencers = manager.numInfluencers;
  66080. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66081. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66082. }
  66083. }
  66084. // Instances
  66085. if (useInstances) {
  66086. defines.push("#define INSTANCES");
  66087. attribs.push("world0");
  66088. attribs.push("world1");
  66089. attribs.push("world2");
  66090. attribs.push("world3");
  66091. }
  66092. // Get correct effect
  66093. var join = defines.join("\n");
  66094. if (this._cachedDefines !== join) {
  66095. this._cachedDefines = join;
  66096. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66097. }
  66098. if (!this._effect.isReady()) {
  66099. return false;
  66100. }
  66101. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66102. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66103. this._initializeBlurRTTAndPostProcesses();
  66104. }
  66105. }
  66106. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66107. return false;
  66108. }
  66109. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66110. return false;
  66111. }
  66112. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66113. return false;
  66114. }
  66115. return true;
  66116. };
  66117. /**
  66118. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66119. * @param defines Defines of the material we want to update
  66120. * @param lightIndex Index of the light in the enabled light list of the material
  66121. */
  66122. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66123. var scene = this._scene;
  66124. var light = this._light;
  66125. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66126. return;
  66127. }
  66128. defines["SHADOW" + lightIndex] = true;
  66129. if (this.useContactHardeningShadow) {
  66130. defines["SHADOWPCSS" + lightIndex] = true;
  66131. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66132. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66133. }
  66134. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66135. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66136. }
  66137. // else default to high.
  66138. }
  66139. if (this.usePercentageCloserFiltering) {
  66140. defines["SHADOWPCF" + lightIndex] = true;
  66141. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66142. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66143. }
  66144. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66145. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66146. }
  66147. // else default to high.
  66148. }
  66149. else if (this.usePoissonSampling) {
  66150. defines["SHADOWPOISSON" + lightIndex] = true;
  66151. }
  66152. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66153. defines["SHADOWESM" + lightIndex] = true;
  66154. }
  66155. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66156. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66157. }
  66158. if (light.needCube()) {
  66159. defines["SHADOWCUBE" + lightIndex] = true;
  66160. }
  66161. };
  66162. /**
  66163. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66164. * defined in the generator but impacting the effect).
  66165. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66166. * @param effect The effect we are binfing the information for
  66167. */
  66168. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66169. var light = this._light;
  66170. var scene = this._scene;
  66171. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66172. return;
  66173. }
  66174. var camera = scene.activeCamera;
  66175. if (!camera) {
  66176. return;
  66177. }
  66178. var shadowMap = this.getShadowMap();
  66179. if (!shadowMap) {
  66180. return;
  66181. }
  66182. if (!light.needCube()) {
  66183. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66184. }
  66185. // Only PCF uses depth stencil texture.
  66186. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66187. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66188. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66189. }
  66190. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66191. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66192. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66193. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66194. }
  66195. else {
  66196. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66197. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66198. }
  66199. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66200. };
  66201. /**
  66202. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66203. * (eq to shadow prjection matrix * light transform matrix)
  66204. * @returns The transform matrix used to create the shadow map
  66205. */
  66206. ShadowGenerator.prototype.getTransformMatrix = function () {
  66207. var scene = this._scene;
  66208. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66209. return this._transformMatrix;
  66210. }
  66211. this._currentRenderID = scene.getRenderId();
  66212. this._currentFaceIndexCache = this._currentFaceIndex;
  66213. var lightPosition = this._light.position;
  66214. if (this._light.computeTransformedInformation()) {
  66215. lightPosition = this._light.transformedPosition;
  66216. }
  66217. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66218. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66219. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66220. }
  66221. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66222. this._cachedPosition.copyFrom(lightPosition);
  66223. this._cachedDirection.copyFrom(this._lightDirection);
  66224. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66225. var shadowMap = this.getShadowMap();
  66226. if (shadowMap) {
  66227. var renderList = shadowMap.renderList;
  66228. if (renderList) {
  66229. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66230. }
  66231. }
  66232. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66233. }
  66234. return this._transformMatrix;
  66235. };
  66236. /**
  66237. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66238. * Cube and 2D textures for instance.
  66239. */
  66240. ShadowGenerator.prototype.recreateShadowMap = function () {
  66241. var shadowMap = this._shadowMap;
  66242. if (!shadowMap) {
  66243. return;
  66244. }
  66245. // Track render list.
  66246. var renderList = shadowMap.renderList;
  66247. // Clean up existing data.
  66248. this._disposeRTTandPostProcesses();
  66249. // Reinitializes.
  66250. this._initializeGenerator();
  66251. // Reaffect the filter to ensure a correct fallback if necessary.
  66252. this.filter = this.filter;
  66253. // Reaffect the filter.
  66254. this._applyFilterValues();
  66255. // Reaffect Render List.
  66256. this._shadowMap.renderList = renderList;
  66257. };
  66258. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66259. if (this._shadowMap2) {
  66260. this._shadowMap2.dispose();
  66261. this._shadowMap2 = null;
  66262. }
  66263. if (this._boxBlurPostprocess) {
  66264. this._boxBlurPostprocess.dispose();
  66265. this._boxBlurPostprocess = null;
  66266. }
  66267. if (this._kernelBlurXPostprocess) {
  66268. this._kernelBlurXPostprocess.dispose();
  66269. this._kernelBlurXPostprocess = null;
  66270. }
  66271. if (this._kernelBlurYPostprocess) {
  66272. this._kernelBlurYPostprocess.dispose();
  66273. this._kernelBlurYPostprocess = null;
  66274. }
  66275. this._blurPostProcesses = [];
  66276. };
  66277. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66278. if (this._shadowMap) {
  66279. this._shadowMap.dispose();
  66280. this._shadowMap = null;
  66281. }
  66282. this._disposeBlurPostProcesses();
  66283. };
  66284. /**
  66285. * Disposes the ShadowGenerator.
  66286. * Returns nothing.
  66287. */
  66288. ShadowGenerator.prototype.dispose = function () {
  66289. this._disposeRTTandPostProcesses();
  66290. if (this._light) {
  66291. this._light._shadowGenerator = null;
  66292. this._light._markMeshesAsLightDirty();
  66293. }
  66294. };
  66295. /**
  66296. * Serializes the shadow generator setup to a json object.
  66297. * @returns The serialized JSON object
  66298. */
  66299. ShadowGenerator.prototype.serialize = function () {
  66300. var serializationObject = {};
  66301. var shadowMap = this.getShadowMap();
  66302. if (!shadowMap) {
  66303. return serializationObject;
  66304. }
  66305. serializationObject.lightId = this._light.id;
  66306. serializationObject.mapSize = shadowMap.getRenderSize();
  66307. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66308. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66309. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66310. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66311. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66312. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66313. serializationObject.depthScale = this.depthScale;
  66314. serializationObject.darkness = this.getDarkness();
  66315. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66316. serializationObject.blurKernel = this.blurKernel;
  66317. serializationObject.blurScale = this.blurScale;
  66318. serializationObject.useKernelBlur = this.useKernelBlur;
  66319. serializationObject.transparencyShadow = this._transparencyShadow;
  66320. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  66321. serializationObject.bias = this.bias;
  66322. serializationObject.normalBias = this.normalBias;
  66323. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66324. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66325. serializationObject.filteringQuality = this.filteringQuality;
  66326. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66327. serializationObject.renderList = [];
  66328. if (shadowMap.renderList) {
  66329. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66330. var mesh = shadowMap.renderList[meshIndex];
  66331. serializationObject.renderList.push(mesh.id);
  66332. }
  66333. }
  66334. return serializationObject;
  66335. };
  66336. /**
  66337. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66338. * @param parsedShadowGenerator The JSON object to parse
  66339. * @param scene The scene to create the shadow map for
  66340. * @returns The parsed shadow generator
  66341. */
  66342. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66343. //casting to point light, as light is missing the position attr and typescript complains.
  66344. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66345. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66346. var shadowMap = shadowGenerator.getShadowMap();
  66347. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66348. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66349. meshes.forEach(function (mesh) {
  66350. if (!shadowMap) {
  66351. return;
  66352. }
  66353. if (!shadowMap.renderList) {
  66354. shadowMap.renderList = [];
  66355. }
  66356. shadowMap.renderList.push(mesh);
  66357. });
  66358. }
  66359. if (parsedShadowGenerator.usePoissonSampling) {
  66360. shadowGenerator.usePoissonSampling = true;
  66361. }
  66362. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66363. shadowGenerator.useExponentialShadowMap = true;
  66364. }
  66365. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66366. shadowGenerator.useBlurExponentialShadowMap = true;
  66367. }
  66368. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66369. shadowGenerator.useCloseExponentialShadowMap = true;
  66370. }
  66371. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66372. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66373. }
  66374. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66375. shadowGenerator.usePercentageCloserFiltering = true;
  66376. }
  66377. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66378. shadowGenerator.useContactHardeningShadow = true;
  66379. }
  66380. if (parsedShadowGenerator.filteringQuality) {
  66381. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66382. }
  66383. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66384. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66385. }
  66386. // Backward compat
  66387. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66388. shadowGenerator.useExponentialShadowMap = true;
  66389. }
  66390. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  66391. shadowGenerator.useBlurExponentialShadowMap = true;
  66392. }
  66393. if (parsedShadowGenerator.depthScale) {
  66394. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  66395. }
  66396. if (parsedShadowGenerator.blurScale) {
  66397. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  66398. }
  66399. if (parsedShadowGenerator.blurBoxOffset) {
  66400. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  66401. }
  66402. if (parsedShadowGenerator.useKernelBlur) {
  66403. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  66404. }
  66405. if (parsedShadowGenerator.blurKernel) {
  66406. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  66407. }
  66408. if (parsedShadowGenerator.bias !== undefined) {
  66409. shadowGenerator.bias = parsedShadowGenerator.bias;
  66410. }
  66411. if (parsedShadowGenerator.normalBias !== undefined) {
  66412. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  66413. }
  66414. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  66415. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  66416. }
  66417. if (parsedShadowGenerator.darkness) {
  66418. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66419. }
  66420. if (parsedShadowGenerator.transparencyShadow) {
  66421. shadowGenerator.setTransparencyShadow(true);
  66422. }
  66423. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66424. return shadowGenerator;
  66425. };
  66426. /**
  66427. * Shadow generator mode None: no filtering applied.
  66428. */
  66429. ShadowGenerator.FILTER_NONE = 0;
  66430. /**
  66431. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66432. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66433. */
  66434. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66435. /**
  66436. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66437. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66438. */
  66439. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66440. /**
  66441. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66442. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66443. */
  66444. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66445. /**
  66446. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66447. * edge artifacts on steep falloff.
  66448. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66449. */
  66450. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66451. /**
  66452. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66453. * edge artifacts on steep falloff.
  66454. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66455. */
  66456. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66457. /**
  66458. * Shadow generator mode PCF: Percentage Closer Filtering
  66459. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66460. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66461. */
  66462. ShadowGenerator.FILTER_PCF = 6;
  66463. /**
  66464. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66465. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66466. * Contact Hardening
  66467. */
  66468. ShadowGenerator.FILTER_PCSS = 7;
  66469. /**
  66470. * Reserved for PCF and PCSS
  66471. * Highest Quality.
  66472. *
  66473. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66474. *
  66475. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66476. */
  66477. ShadowGenerator.QUALITY_HIGH = 0;
  66478. /**
  66479. * Reserved for PCF and PCSS
  66480. * Good tradeoff for quality/perf cross devices
  66481. *
  66482. * Execute PCF on a 3*3 kernel.
  66483. *
  66484. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66485. */
  66486. ShadowGenerator.QUALITY_MEDIUM = 1;
  66487. /**
  66488. * Reserved for PCF and PCSS
  66489. * The lowest quality but the fastest.
  66490. *
  66491. * Execute PCF on a 1*1 kernel.
  66492. *
  66493. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66494. */
  66495. ShadowGenerator.QUALITY_LOW = 2;
  66496. return ShadowGenerator;
  66497. }());
  66498. BABYLON.ShadowGenerator = ShadowGenerator;
  66499. })(BABYLON || (BABYLON = {}));
  66500. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66501. var BABYLON;
  66502. (function (BABYLON) {
  66503. var DefaultLoadingScreen = /** @class */ (function () {
  66504. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66505. if (_loadingText === void 0) { _loadingText = ""; }
  66506. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66507. var _this = this;
  66508. this._renderingCanvas = _renderingCanvas;
  66509. this._loadingText = _loadingText;
  66510. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66511. // Resize
  66512. this._resizeLoadingUI = function () {
  66513. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66514. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66515. if (!_this._loadingDiv) {
  66516. return;
  66517. }
  66518. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66519. _this._loadingDiv.style.left = canvasRect.left + "px";
  66520. _this._loadingDiv.style.top = canvasRect.top + "px";
  66521. _this._loadingDiv.style.width = canvasRect.width + "px";
  66522. _this._loadingDiv.style.height = canvasRect.height + "px";
  66523. };
  66524. }
  66525. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  66526. if (this._loadingDiv) {
  66527. // Do not add a loading screen if there is already one
  66528. return;
  66529. }
  66530. this._loadingDiv = document.createElement("div");
  66531. this._loadingDiv.id = "babylonjsLoadingDiv";
  66532. this._loadingDiv.style.opacity = "0";
  66533. this._loadingDiv.style.transition = "opacity 1.5s ease";
  66534. this._loadingDiv.style.pointerEvents = "none";
  66535. // Loading text
  66536. this._loadingTextDiv = document.createElement("div");
  66537. this._loadingTextDiv.style.position = "absolute";
  66538. this._loadingTextDiv.style.left = "0";
  66539. this._loadingTextDiv.style.top = "50%";
  66540. this._loadingTextDiv.style.marginTop = "80px";
  66541. this._loadingTextDiv.style.width = "100%";
  66542. this._loadingTextDiv.style.height = "20px";
  66543. this._loadingTextDiv.style.fontFamily = "Arial";
  66544. this._loadingTextDiv.style.fontSize = "14px";
  66545. this._loadingTextDiv.style.color = "white";
  66546. this._loadingTextDiv.style.textAlign = "center";
  66547. this._loadingTextDiv.innerHTML = "Loading";
  66548. this._loadingDiv.appendChild(this._loadingTextDiv);
  66549. //set the predefined text
  66550. this._loadingTextDiv.innerHTML = this._loadingText;
  66551. // Generating keyframes
  66552. var style = document.createElement('style');
  66553. style.type = 'text/css';
  66554. 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 }";
  66555. style.innerHTML = keyFrames;
  66556. document.getElementsByTagName('head')[0].appendChild(style);
  66557. // Loading img
  66558. var imgBack = new Image();
  66559. 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";
  66560. imgBack.style.position = "absolute";
  66561. imgBack.style.left = "50%";
  66562. imgBack.style.top = "50%";
  66563. imgBack.style.marginLeft = "-60px";
  66564. imgBack.style.marginTop = "-60px";
  66565. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  66566. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  66567. imgBack.style.transformOrigin = "50% 50%";
  66568. imgBack.style.webkitTransformOrigin = "50% 50%";
  66569. this._loadingDiv.appendChild(imgBack);
  66570. this._resizeLoadingUI();
  66571. window.addEventListener("resize", this._resizeLoadingUI);
  66572. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66573. document.body.appendChild(this._loadingDiv);
  66574. this._loadingDiv.style.opacity = "1";
  66575. };
  66576. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  66577. var _this = this;
  66578. if (!this._loadingDiv) {
  66579. return;
  66580. }
  66581. var onTransitionEnd = function () {
  66582. if (!_this._loadingDiv) {
  66583. return;
  66584. }
  66585. document.body.removeChild(_this._loadingDiv);
  66586. window.removeEventListener("resize", _this._resizeLoadingUI);
  66587. _this._loadingDiv = null;
  66588. };
  66589. this._loadingDiv.style.opacity = "0";
  66590. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  66591. };
  66592. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  66593. set: function (text) {
  66594. this._loadingText = text;
  66595. if (this._loadingTextDiv) {
  66596. this._loadingTextDiv.innerHTML = this._loadingText;
  66597. }
  66598. },
  66599. enumerable: true,
  66600. configurable: true
  66601. });
  66602. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  66603. get: function () {
  66604. return this._loadingDivBackgroundColor;
  66605. },
  66606. set: function (color) {
  66607. this._loadingDivBackgroundColor = color;
  66608. if (!this._loadingDiv) {
  66609. return;
  66610. }
  66611. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66612. },
  66613. enumerable: true,
  66614. configurable: true
  66615. });
  66616. return DefaultLoadingScreen;
  66617. }());
  66618. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  66619. })(BABYLON || (BABYLON = {}));
  66620. //# sourceMappingURL=babylon.loadingScreen.js.map
  66621. var BABYLON;
  66622. (function (BABYLON) {
  66623. var SceneLoaderProgressEvent = /** @class */ (function () {
  66624. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  66625. this.lengthComputable = lengthComputable;
  66626. this.loaded = loaded;
  66627. this.total = total;
  66628. }
  66629. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  66630. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  66631. };
  66632. return SceneLoaderProgressEvent;
  66633. }());
  66634. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  66635. var SceneLoader = /** @class */ (function () {
  66636. function SceneLoader() {
  66637. }
  66638. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  66639. get: function () {
  66640. return 0;
  66641. },
  66642. enumerable: true,
  66643. configurable: true
  66644. });
  66645. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  66646. get: function () {
  66647. return 1;
  66648. },
  66649. enumerable: true,
  66650. configurable: true
  66651. });
  66652. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  66653. get: function () {
  66654. return 2;
  66655. },
  66656. enumerable: true,
  66657. configurable: true
  66658. });
  66659. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  66660. get: function () {
  66661. return 3;
  66662. },
  66663. enumerable: true,
  66664. configurable: true
  66665. });
  66666. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  66667. get: function () {
  66668. return SceneLoader._ForceFullSceneLoadingForIncremental;
  66669. },
  66670. set: function (value) {
  66671. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  66672. },
  66673. enumerable: true,
  66674. configurable: true
  66675. });
  66676. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  66677. get: function () {
  66678. return SceneLoader._ShowLoadingScreen;
  66679. },
  66680. set: function (value) {
  66681. SceneLoader._ShowLoadingScreen = value;
  66682. },
  66683. enumerable: true,
  66684. configurable: true
  66685. });
  66686. Object.defineProperty(SceneLoader, "loggingLevel", {
  66687. get: function () {
  66688. return SceneLoader._loggingLevel;
  66689. },
  66690. set: function (value) {
  66691. SceneLoader._loggingLevel = value;
  66692. },
  66693. enumerable: true,
  66694. configurable: true
  66695. });
  66696. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  66697. get: function () {
  66698. return SceneLoader._CleanBoneMatrixWeights;
  66699. },
  66700. set: function (value) {
  66701. SceneLoader._CleanBoneMatrixWeights = value;
  66702. },
  66703. enumerable: true,
  66704. configurable: true
  66705. });
  66706. SceneLoader._getDefaultPlugin = function () {
  66707. return SceneLoader._registeredPlugins[".babylon"];
  66708. };
  66709. SceneLoader._getPluginForExtension = function (extension) {
  66710. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  66711. if (registeredPlugin) {
  66712. return registeredPlugin;
  66713. }
  66714. 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");
  66715. return SceneLoader._getDefaultPlugin();
  66716. };
  66717. SceneLoader._getPluginForDirectLoad = function (data) {
  66718. for (var extension in SceneLoader._registeredPlugins) {
  66719. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  66720. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  66721. return SceneLoader._registeredPlugins[extension];
  66722. }
  66723. }
  66724. return SceneLoader._getDefaultPlugin();
  66725. };
  66726. SceneLoader._getPluginForFilename = function (sceneFilename) {
  66727. if (sceneFilename.name) {
  66728. sceneFilename = sceneFilename.name;
  66729. }
  66730. var queryStringPosition = sceneFilename.indexOf("?");
  66731. if (queryStringPosition !== -1) {
  66732. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  66733. }
  66734. var dotPosition = sceneFilename.lastIndexOf(".");
  66735. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  66736. return SceneLoader._getPluginForExtension(extension);
  66737. };
  66738. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  66739. SceneLoader._getDirectLoad = function (sceneFilename) {
  66740. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  66741. return sceneFilename.substr(5);
  66742. }
  66743. return null;
  66744. };
  66745. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  66746. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  66747. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  66748. var plugin;
  66749. if (registeredPlugin.plugin.createPlugin) {
  66750. plugin = registeredPlugin.plugin.createPlugin();
  66751. }
  66752. else {
  66753. plugin = registeredPlugin.plugin;
  66754. }
  66755. var useArrayBuffer = registeredPlugin.isBinary;
  66756. var database;
  66757. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  66758. var dataCallback = function (data, responseURL) {
  66759. if (scene.isDisposed) {
  66760. onError("Scene has been disposed");
  66761. return;
  66762. }
  66763. scene.database = database;
  66764. onSuccess(plugin, data, responseURL);
  66765. };
  66766. var request = null;
  66767. var pluginDisposed = false;
  66768. var onDisposeObservable = plugin.onDisposeObservable;
  66769. if (onDisposeObservable) {
  66770. onDisposeObservable.add(function () {
  66771. pluginDisposed = true;
  66772. if (request) {
  66773. request.abort();
  66774. request = null;
  66775. }
  66776. onDispose();
  66777. });
  66778. }
  66779. var manifestChecked = function () {
  66780. if (pluginDisposed) {
  66781. return;
  66782. }
  66783. var url = rootUrl + sceneFilename;
  66784. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  66785. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  66786. } : undefined, database, useArrayBuffer, function (request, exception) {
  66787. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  66788. });
  66789. };
  66790. if (directLoad) {
  66791. dataCallback(directLoad);
  66792. return plugin;
  66793. }
  66794. if (rootUrl.indexOf("file:") === -1) {
  66795. var engine = scene.getEngine();
  66796. var canUseOfflineSupport = engine.enableOfflineSupport;
  66797. if (canUseOfflineSupport) {
  66798. // Also check for exceptions
  66799. var exceptionFound = false;
  66800. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  66801. var regex = _a[_i];
  66802. if (regex.test(rootUrl + sceneFilename)) {
  66803. exceptionFound = true;
  66804. break;
  66805. }
  66806. }
  66807. canUseOfflineSupport = !exceptionFound;
  66808. }
  66809. if (canUseOfflineSupport) {
  66810. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  66811. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  66812. }
  66813. else {
  66814. manifestChecked();
  66815. }
  66816. }
  66817. // Loading file from disk via input file or drag'n'drop
  66818. else {
  66819. var fileOrString = sceneFilename;
  66820. if (fileOrString.name) { // File
  66821. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  66822. }
  66823. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  66824. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  66825. }
  66826. else {
  66827. onError("Unable to find file named " + sceneFilename);
  66828. }
  66829. }
  66830. return plugin;
  66831. };
  66832. // Public functions
  66833. SceneLoader.GetPluginForExtension = function (extension) {
  66834. return SceneLoader._getPluginForExtension(extension).plugin;
  66835. };
  66836. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  66837. return !!SceneLoader._registeredPlugins[extension];
  66838. };
  66839. SceneLoader.RegisterPlugin = function (plugin) {
  66840. if (typeof plugin.extensions === "string") {
  66841. var extension = plugin.extensions;
  66842. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66843. plugin: plugin,
  66844. isBinary: false
  66845. };
  66846. }
  66847. else {
  66848. var extensions = plugin.extensions;
  66849. Object.keys(extensions).forEach(function (extension) {
  66850. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66851. plugin: plugin,
  66852. isBinary: extensions[extension].isBinary
  66853. };
  66854. });
  66855. }
  66856. };
  66857. /**
  66858. * Import meshes into a scene
  66859. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66860. * @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)
  66861. * @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)
  66862. * @param scene the instance of BABYLON.Scene to append to
  66863. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  66864. * @param onProgress a callback with a progress event for each file being loaded
  66865. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66866. * @param pluginExtension the extension used to determine the plugin
  66867. * @returns The loaded plugin
  66868. */
  66869. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66870. if (sceneFilename === void 0) { sceneFilename = ""; }
  66871. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  66872. if (onSuccess === void 0) { onSuccess = null; }
  66873. if (onProgress === void 0) { onProgress = null; }
  66874. if (onError === void 0) { onError = null; }
  66875. if (pluginExtension === void 0) { pluginExtension = null; }
  66876. if (!scene) {
  66877. BABYLON.Tools.Error("No scene available to import mesh to");
  66878. return null;
  66879. }
  66880. if (!sceneFilename) {
  66881. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  66882. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  66883. }
  66884. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66885. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66886. return null;
  66887. }
  66888. var loadingToken = {};
  66889. scene._addPendingData(loadingToken);
  66890. var disposeHandler = function () {
  66891. scene._removePendingData(loadingToken);
  66892. };
  66893. var errorHandler = function (message, exception) {
  66894. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  66895. if (onError) {
  66896. onError(scene, errorMessage, exception);
  66897. }
  66898. else {
  66899. BABYLON.Tools.Error(errorMessage);
  66900. // should the exception be thrown?
  66901. }
  66902. disposeHandler();
  66903. };
  66904. var progressHandler = onProgress ? function (event) {
  66905. try {
  66906. onProgress(event);
  66907. }
  66908. catch (e) {
  66909. errorHandler("Error in onProgress callback", e);
  66910. }
  66911. } : undefined;
  66912. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  66913. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  66914. if (onSuccess) {
  66915. try {
  66916. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  66917. }
  66918. catch (e) {
  66919. errorHandler("Error in onSuccess callback", e);
  66920. }
  66921. }
  66922. scene._removePendingData(loadingToken);
  66923. };
  66924. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66925. if (plugin.rewriteRootURL) {
  66926. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  66927. }
  66928. if (sceneFilename === "") {
  66929. if (sceneFilename === "") {
  66930. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  66931. }
  66932. }
  66933. if (plugin.importMesh) {
  66934. var syncedPlugin = plugin;
  66935. var meshes = new Array();
  66936. var particleSystems = new Array();
  66937. var skeletons = new Array();
  66938. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  66939. return;
  66940. }
  66941. scene.loadingPluginName = plugin.name;
  66942. successHandler(meshes, particleSystems, skeletons, []);
  66943. }
  66944. else {
  66945. var asyncedPlugin = plugin;
  66946. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  66947. scene.loadingPluginName = plugin.name;
  66948. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  66949. }).catch(function (error) {
  66950. errorHandler(error.message, error);
  66951. });
  66952. }
  66953. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66954. };
  66955. /**
  66956. * Import meshes into a scene
  66957. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66958. * @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)
  66959. * @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)
  66960. * @param scene the instance of BABYLON.Scene to append to
  66961. * @param onProgress a callback with a progress event for each file being loaded
  66962. * @param pluginExtension the extension used to determine the plugin
  66963. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  66964. */
  66965. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66966. if (sceneFilename === void 0) { sceneFilename = ""; }
  66967. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  66968. if (onProgress === void 0) { onProgress = null; }
  66969. if (pluginExtension === void 0) { pluginExtension = null; }
  66970. return new Promise(function (resolve, reject) {
  66971. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  66972. resolve({
  66973. meshes: meshes,
  66974. particleSystems: particleSystems,
  66975. skeletons: skeletons,
  66976. animationGroups: animationGroups
  66977. });
  66978. }, onProgress, function (scene, message, exception) {
  66979. reject(exception || new Error(message));
  66980. }, pluginExtension);
  66981. });
  66982. };
  66983. /**
  66984. * Load a scene
  66985. * @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)
  66986. * @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)
  66987. * @param engine is the instance of BABYLON.Engine to use to create the scene
  66988. * @param onSuccess a callback with the scene when import succeeds
  66989. * @param onProgress a callback with a progress event for each file being loaded
  66990. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66991. * @param pluginExtension the extension used to determine the plugin
  66992. * @returns The loaded plugin
  66993. */
  66994. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  66995. if (onSuccess === void 0) { onSuccess = null; }
  66996. if (onProgress === void 0) { onProgress = null; }
  66997. if (onError === void 0) { onError = null; }
  66998. if (pluginExtension === void 0) { pluginExtension = null; }
  66999. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67000. };
  67001. /**
  67002. * Load a scene
  67003. * @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)
  67004. * @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)
  67005. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67006. * @param onProgress a callback with a progress event for each file being loaded
  67007. * @param pluginExtension the extension used to determine the plugin
  67008. * @returns The loaded scene
  67009. */
  67010. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67011. if (onProgress === void 0) { onProgress = null; }
  67012. if (pluginExtension === void 0) { pluginExtension = null; }
  67013. return new Promise(function (resolve, reject) {
  67014. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67015. resolve(scene);
  67016. }, onProgress, function (scene, message, exception) {
  67017. reject(exception || new Error(message));
  67018. }, pluginExtension);
  67019. });
  67020. };
  67021. /**
  67022. * Append a scene
  67023. * @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)
  67024. * @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)
  67025. * @param scene is the instance of BABYLON.Scene to append to
  67026. * @param onSuccess a callback with the scene when import succeeds
  67027. * @param onProgress a callback with a progress event for each file being loaded
  67028. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67029. * @param pluginExtension the extension used to determine the plugin
  67030. * @returns The loaded plugin
  67031. */
  67032. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67033. if (sceneFilename === void 0) { sceneFilename = ""; }
  67034. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67035. if (onSuccess === void 0) { onSuccess = null; }
  67036. if (onProgress === void 0) { onProgress = null; }
  67037. if (onError === void 0) { onError = null; }
  67038. if (pluginExtension === void 0) { pluginExtension = null; }
  67039. if (!scene) {
  67040. BABYLON.Tools.Error("No scene available to append to");
  67041. return null;
  67042. }
  67043. if (!sceneFilename) {
  67044. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67045. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67046. }
  67047. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67048. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67049. return null;
  67050. }
  67051. if (SceneLoader.ShowLoadingScreen) {
  67052. scene.getEngine().displayLoadingUI();
  67053. }
  67054. var loadingToken = {};
  67055. scene._addPendingData(loadingToken);
  67056. var disposeHandler = function () {
  67057. scene._removePendingData(loadingToken);
  67058. scene.getEngine().hideLoadingUI();
  67059. };
  67060. var errorHandler = function (message, exception) {
  67061. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67062. if (onError) {
  67063. onError(scene, errorMessage, exception);
  67064. }
  67065. else {
  67066. BABYLON.Tools.Error(errorMessage);
  67067. // should the exception be thrown?
  67068. }
  67069. disposeHandler();
  67070. };
  67071. var progressHandler = onProgress ? function (event) {
  67072. try {
  67073. onProgress(event);
  67074. }
  67075. catch (e) {
  67076. errorHandler("Error in onProgress callback", e);
  67077. }
  67078. } : undefined;
  67079. var successHandler = function () {
  67080. if (onSuccess) {
  67081. try {
  67082. onSuccess(scene);
  67083. }
  67084. catch (e) {
  67085. errorHandler("Error in onSuccess callback", e);
  67086. }
  67087. }
  67088. scene._removePendingData(loadingToken);
  67089. };
  67090. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67091. if (sceneFilename === "") {
  67092. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67093. }
  67094. if (plugin.load) {
  67095. var syncedPlugin = plugin;
  67096. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67097. return;
  67098. }
  67099. scene.loadingPluginName = plugin.name;
  67100. successHandler();
  67101. }
  67102. else {
  67103. var asyncedPlugin = plugin;
  67104. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67105. scene.loadingPluginName = plugin.name;
  67106. successHandler();
  67107. }).catch(function (error) {
  67108. errorHandler(error.message, error);
  67109. });
  67110. }
  67111. if (SceneLoader.ShowLoadingScreen) {
  67112. scene.executeWhenReady(function () {
  67113. scene.getEngine().hideLoadingUI();
  67114. });
  67115. }
  67116. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67117. };
  67118. /**
  67119. * Append a scene
  67120. * @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)
  67121. * @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)
  67122. * @param scene is the instance of BABYLON.Scene to append to
  67123. * @param onProgress a callback with a progress event for each file being loaded
  67124. * @param pluginExtension the extension used to determine the plugin
  67125. * @returns The given scene
  67126. */
  67127. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67128. if (sceneFilename === void 0) { sceneFilename = ""; }
  67129. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67130. if (onProgress === void 0) { onProgress = null; }
  67131. if (pluginExtension === void 0) { pluginExtension = null; }
  67132. return new Promise(function (resolve, reject) {
  67133. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67134. resolve(scene);
  67135. }, onProgress, function (scene, message, exception) {
  67136. reject(exception || new Error(message));
  67137. }, pluginExtension);
  67138. });
  67139. };
  67140. /**
  67141. * Load a scene into an asset container
  67142. * @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)
  67143. * @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)
  67144. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  67145. * @param onSuccess a callback with the scene when import succeeds
  67146. * @param onProgress a callback with a progress event for each file being loaded
  67147. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67148. * @param pluginExtension the extension used to determine the plugin
  67149. * @returns The loaded plugin
  67150. */
  67151. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67152. if (sceneFilename === void 0) { sceneFilename = ""; }
  67153. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67154. if (onSuccess === void 0) { onSuccess = null; }
  67155. if (onProgress === void 0) { onProgress = null; }
  67156. if (onError === void 0) { onError = null; }
  67157. if (pluginExtension === void 0) { pluginExtension = null; }
  67158. if (!scene) {
  67159. BABYLON.Tools.Error("No scene available to load asset container to");
  67160. return null;
  67161. }
  67162. if (!sceneFilename) {
  67163. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67164. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67165. }
  67166. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67167. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67168. return null;
  67169. }
  67170. var loadingToken = {};
  67171. scene._addPendingData(loadingToken);
  67172. var disposeHandler = function () {
  67173. scene._removePendingData(loadingToken);
  67174. };
  67175. var errorHandler = function (message, exception) {
  67176. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67177. if (onError) {
  67178. onError(scene, errorMessage, exception);
  67179. }
  67180. else {
  67181. BABYLON.Tools.Error(errorMessage);
  67182. // should the exception be thrown?
  67183. }
  67184. disposeHandler();
  67185. };
  67186. var progressHandler = onProgress ? function (event) {
  67187. try {
  67188. onProgress(event);
  67189. }
  67190. catch (e) {
  67191. errorHandler("Error in onProgress callback", e);
  67192. }
  67193. } : undefined;
  67194. var successHandler = function (assets) {
  67195. if (onSuccess) {
  67196. try {
  67197. onSuccess(assets);
  67198. }
  67199. catch (e) {
  67200. errorHandler("Error in onSuccess callback", e);
  67201. }
  67202. }
  67203. scene._removePendingData(loadingToken);
  67204. };
  67205. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67206. if (plugin.loadAssetContainer) {
  67207. var syncedPlugin = plugin;
  67208. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67209. if (!assetContainer) {
  67210. return;
  67211. }
  67212. scene.loadingPluginName = plugin.name;
  67213. successHandler(assetContainer);
  67214. }
  67215. else if (plugin.loadAssetContainerAsync) {
  67216. var asyncedPlugin = plugin;
  67217. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67218. scene.loadingPluginName = plugin.name;
  67219. successHandler(assetContainer);
  67220. }).catch(function (error) {
  67221. errorHandler(error.message, error);
  67222. });
  67223. }
  67224. else {
  67225. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67226. }
  67227. if (SceneLoader.ShowLoadingScreen) {
  67228. scene.executeWhenReady(function () {
  67229. scene.getEngine().hideLoadingUI();
  67230. });
  67231. }
  67232. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67233. };
  67234. /**
  67235. * Load a scene into an asset container
  67236. * @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)
  67237. * @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)
  67238. * @param scene is the instance of BABYLON.Scene to append to
  67239. * @param onProgress a callback with a progress event for each file being loaded
  67240. * @param pluginExtension the extension used to determine the plugin
  67241. * @returns The loaded asset container
  67242. */
  67243. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67244. if (sceneFilename === void 0) { sceneFilename = ""; }
  67245. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67246. if (onProgress === void 0) { onProgress = null; }
  67247. if (pluginExtension === void 0) { pluginExtension = null; }
  67248. return new Promise(function (resolve, reject) {
  67249. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67250. resolve(assetContainer);
  67251. }, onProgress, function (scene, message, exception) {
  67252. reject(exception || new Error(message));
  67253. }, pluginExtension);
  67254. });
  67255. };
  67256. // Flags
  67257. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67258. SceneLoader._ShowLoadingScreen = true;
  67259. SceneLoader._CleanBoneMatrixWeights = false;
  67260. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67261. // Members
  67262. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67263. SceneLoader._registeredPlugins = {};
  67264. return SceneLoader;
  67265. }());
  67266. BABYLON.SceneLoader = SceneLoader;
  67267. ;
  67268. })(BABYLON || (BABYLON = {}));
  67269. //# sourceMappingURL=babylon.sceneLoader.js.map
  67270. var BABYLON;
  67271. (function (BABYLON) {
  67272. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67273. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67274. var parsedMaterial = parsedData.materials[index];
  67275. if (parsedMaterial.id === id) {
  67276. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67277. }
  67278. }
  67279. return null;
  67280. };
  67281. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67282. for (var i in names) {
  67283. if (mesh.name === names[i]) {
  67284. hierarchyIds.push(mesh.id);
  67285. return true;
  67286. }
  67287. }
  67288. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67289. hierarchyIds.push(mesh.id);
  67290. return true;
  67291. }
  67292. return false;
  67293. };
  67294. var logOperation = function (operation, producer) {
  67295. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67296. };
  67297. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67298. if (addToScene === void 0) { addToScene = false; }
  67299. var container = new BABYLON.AssetContainer(scene);
  67300. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67301. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67302. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67303. // and avoid problems with multiple concurrent .babylon loads.
  67304. var log = "importScene has failed JSON parse";
  67305. try {
  67306. var parsedData = JSON.parse(data);
  67307. log = "";
  67308. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67309. var index;
  67310. var cache;
  67311. // Lights
  67312. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67313. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67314. var parsedLight = parsedData.lights[index];
  67315. var light = BABYLON.Light.Parse(parsedLight, scene);
  67316. if (light) {
  67317. container.lights.push(light);
  67318. log += (index === 0 ? "\n\tLights:" : "");
  67319. log += "\n\t\t" + light.toString(fullDetails);
  67320. }
  67321. }
  67322. }
  67323. // Animations
  67324. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67325. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67326. var parsedAnimation = parsedData.animations[index];
  67327. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67328. scene.animations.push(animation);
  67329. container.animations.push(animation);
  67330. log += (index === 0 ? "\n\tAnimations:" : "");
  67331. log += "\n\t\t" + animation.toString(fullDetails);
  67332. }
  67333. }
  67334. // Materials
  67335. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67336. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67337. var parsedMaterial = parsedData.materials[index];
  67338. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67339. container.materials.push(mat);
  67340. log += (index === 0 ? "\n\tMaterials:" : "");
  67341. log += "\n\t\t" + mat.toString(fullDetails);
  67342. }
  67343. }
  67344. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67345. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67346. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67347. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67348. container.multiMaterials.push(mmat);
  67349. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67350. log += "\n\t\t" + mmat.toString(fullDetails);
  67351. }
  67352. }
  67353. // Morph targets
  67354. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67355. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67356. var managerData = _a[_i];
  67357. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67358. }
  67359. }
  67360. // Skeletons
  67361. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67362. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67363. var parsedSkeleton = parsedData.skeletons[index];
  67364. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67365. container.skeletons.push(skeleton);
  67366. log += (index === 0 ? "\n\tSkeletons:" : "");
  67367. log += "\n\t\t" + skeleton.toString(fullDetails);
  67368. }
  67369. }
  67370. // Geometries
  67371. var geometries = parsedData.geometries;
  67372. if (geometries !== undefined && geometries !== null) {
  67373. var addedGeometry = new Array();
  67374. // Boxes
  67375. var boxes = geometries.boxes;
  67376. if (boxes !== undefined && boxes !== null) {
  67377. for (index = 0, cache = boxes.length; index < cache; index++) {
  67378. var parsedBox = boxes[index];
  67379. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67380. }
  67381. }
  67382. // Spheres
  67383. var spheres = geometries.spheres;
  67384. if (spheres !== undefined && spheres !== null) {
  67385. for (index = 0, cache = spheres.length; index < cache; index++) {
  67386. var parsedSphere = spheres[index];
  67387. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67388. }
  67389. }
  67390. // Cylinders
  67391. var cylinders = geometries.cylinders;
  67392. if (cylinders !== undefined && cylinders !== null) {
  67393. for (index = 0, cache = cylinders.length; index < cache; index++) {
  67394. var parsedCylinder = cylinders[index];
  67395. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  67396. }
  67397. }
  67398. // Toruses
  67399. var toruses = geometries.toruses;
  67400. if (toruses !== undefined && toruses !== null) {
  67401. for (index = 0, cache = toruses.length; index < cache; index++) {
  67402. var parsedTorus = toruses[index];
  67403. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  67404. }
  67405. }
  67406. // Grounds
  67407. var grounds = geometries.grounds;
  67408. if (grounds !== undefined && grounds !== null) {
  67409. for (index = 0, cache = grounds.length; index < cache; index++) {
  67410. var parsedGround = grounds[index];
  67411. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  67412. }
  67413. }
  67414. // Planes
  67415. var planes = geometries.planes;
  67416. if (planes !== undefined && planes !== null) {
  67417. for (index = 0, cache = planes.length; index < cache; index++) {
  67418. var parsedPlane = planes[index];
  67419. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  67420. }
  67421. }
  67422. // TorusKnots
  67423. var torusKnots = geometries.torusKnots;
  67424. if (torusKnots !== undefined && torusKnots !== null) {
  67425. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  67426. var parsedTorusKnot = torusKnots[index];
  67427. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  67428. }
  67429. }
  67430. // VertexData
  67431. var vertexData = geometries.vertexData;
  67432. if (vertexData !== undefined && vertexData !== null) {
  67433. for (index = 0, cache = vertexData.length; index < cache; index++) {
  67434. var parsedVertexData = vertexData[index];
  67435. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  67436. }
  67437. }
  67438. addedGeometry.forEach(function (g) {
  67439. if (g) {
  67440. container.geometries.push(g);
  67441. }
  67442. });
  67443. }
  67444. // Transform nodes
  67445. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  67446. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  67447. var parsedTransformNode = parsedData.transformNodes[index];
  67448. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  67449. container.transformNodes.push(node);
  67450. }
  67451. }
  67452. // Meshes
  67453. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67454. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67455. var parsedMesh = parsedData.meshes[index];
  67456. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67457. container.meshes.push(mesh);
  67458. log += (index === 0 ? "\n\tMeshes:" : "");
  67459. log += "\n\t\t" + mesh.toString(fullDetails);
  67460. }
  67461. }
  67462. // Cameras
  67463. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67464. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67465. var parsedCamera = parsedData.cameras[index];
  67466. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67467. container.cameras.push(camera);
  67468. log += (index === 0 ? "\n\tCameras:" : "");
  67469. log += "\n\t\t" + camera.toString(fullDetails);
  67470. }
  67471. }
  67472. // Browsing all the graph to connect the dots
  67473. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67474. var camera = scene.cameras[index];
  67475. if (camera._waitingParentId) {
  67476. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  67477. camera._waitingParentId = null;
  67478. }
  67479. }
  67480. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67481. var light_1 = scene.lights[index];
  67482. if (light_1 && light_1._waitingParentId) {
  67483. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  67484. light_1._waitingParentId = null;
  67485. }
  67486. }
  67487. // Sounds
  67488. // TODO: add sound
  67489. var loadedSounds = [];
  67490. var loadedSound;
  67491. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67492. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67493. var parsedSound = parsedData.sounds[index];
  67494. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67495. if (!parsedSound.url)
  67496. parsedSound.url = parsedSound.name;
  67497. if (!loadedSounds[parsedSound.url]) {
  67498. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67499. loadedSounds[parsedSound.url] = loadedSound;
  67500. container.sounds.push(loadedSound);
  67501. }
  67502. else {
  67503. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67504. }
  67505. }
  67506. else {
  67507. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67508. }
  67509. }
  67510. }
  67511. loadedSounds = [];
  67512. // Connect parents & children and parse actions
  67513. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  67514. var transformNode = scene.transformNodes[index];
  67515. if (transformNode._waitingParentId) {
  67516. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67517. transformNode._waitingParentId = null;
  67518. }
  67519. }
  67520. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67521. var mesh = scene.meshes[index];
  67522. if (mesh._waitingParentId) {
  67523. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  67524. mesh._waitingParentId = null;
  67525. }
  67526. if (mesh._waitingActions) {
  67527. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  67528. mesh._waitingActions = null;
  67529. }
  67530. }
  67531. // freeze world matrix application
  67532. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67533. var currentMesh = scene.meshes[index];
  67534. if (currentMesh._waitingFreezeWorldMatrix) {
  67535. currentMesh.freezeWorldMatrix();
  67536. currentMesh._waitingFreezeWorldMatrix = null;
  67537. }
  67538. else {
  67539. currentMesh.computeWorldMatrix(true);
  67540. }
  67541. }
  67542. // Particles Systems
  67543. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67544. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67545. var parsedParticleSystem = parsedData.particleSystems[index];
  67546. if (parsedParticleSystem.activeParticleCount) {
  67547. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67548. container.particleSystems.push(ps);
  67549. }
  67550. else {
  67551. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67552. container.particleSystems.push(ps);
  67553. }
  67554. }
  67555. }
  67556. // Lens flares
  67557. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  67558. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  67559. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  67560. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  67561. container.lensFlareSystems.push(lf);
  67562. }
  67563. }
  67564. // Shadows
  67565. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  67566. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  67567. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  67568. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  67569. container.shadowGenerators.push(sg);
  67570. }
  67571. }
  67572. // Lights exclusions / inclusions
  67573. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67574. var light_2 = scene.lights[index];
  67575. // Excluded check
  67576. if (light_2._excludedMeshesIds.length > 0) {
  67577. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  67578. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  67579. if (excludedMesh) {
  67580. light_2.excludedMeshes.push(excludedMesh);
  67581. }
  67582. }
  67583. light_2._excludedMeshesIds = [];
  67584. }
  67585. // Included check
  67586. if (light_2._includedOnlyMeshesIds.length > 0) {
  67587. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  67588. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  67589. if (includedOnlyMesh) {
  67590. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  67591. }
  67592. }
  67593. light_2._includedOnlyMeshesIds = [];
  67594. }
  67595. }
  67596. // Effect layers
  67597. if (parsedData.effectLayers) {
  67598. for (index = 0; index < parsedData.effectLayers.length; index++) {
  67599. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  67600. container.effectLayers.push(effectLayer);
  67601. }
  67602. }
  67603. // Actions (scene)
  67604. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  67605. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  67606. }
  67607. if (!addToScene) {
  67608. container.removeAllFromScene();
  67609. }
  67610. }
  67611. catch (err) {
  67612. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  67613. if (onError) {
  67614. onError(msg, err);
  67615. }
  67616. else {
  67617. BABYLON.Tools.Log(msg);
  67618. throw err;
  67619. }
  67620. }
  67621. finally {
  67622. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67623. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67624. }
  67625. }
  67626. return container;
  67627. };
  67628. BABYLON.SceneLoader.RegisterPlugin({
  67629. name: "babylon.js",
  67630. extensions: ".babylon",
  67631. canDirectLoad: function (data) {
  67632. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  67633. return true;
  67634. }
  67635. return false;
  67636. },
  67637. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  67638. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67639. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67640. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67641. // and avoid problems with multiple concurrent .babylon loads.
  67642. var log = "importMesh has failed JSON parse";
  67643. try {
  67644. var parsedData = JSON.parse(data);
  67645. log = "";
  67646. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67647. if (!meshesNames) {
  67648. meshesNames = null;
  67649. }
  67650. else if (!Array.isArray(meshesNames)) {
  67651. meshesNames = [meshesNames];
  67652. }
  67653. var hierarchyIds = new Array();
  67654. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67655. var loadedSkeletonsIds = [];
  67656. var loadedMaterialsIds = [];
  67657. var index;
  67658. var cache;
  67659. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67660. var parsedMesh = parsedData.meshes[index];
  67661. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  67662. if (meshesNames !== null) {
  67663. // Remove found mesh name from list.
  67664. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  67665. }
  67666. //Geometry?
  67667. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  67668. //does the file contain geometries?
  67669. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  67670. //find the correct geometry and add it to the scene
  67671. var found = false;
  67672. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  67673. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  67674. return;
  67675. }
  67676. else {
  67677. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  67678. if (parsedGeometryData.id === parsedMesh.geometryId) {
  67679. switch (geometryType) {
  67680. case "boxes":
  67681. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  67682. break;
  67683. case "spheres":
  67684. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  67685. break;
  67686. case "cylinders":
  67687. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  67688. break;
  67689. case "toruses":
  67690. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  67691. break;
  67692. case "grounds":
  67693. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  67694. break;
  67695. case "planes":
  67696. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  67697. break;
  67698. case "torusKnots":
  67699. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  67700. break;
  67701. case "vertexData":
  67702. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  67703. break;
  67704. }
  67705. found = true;
  67706. }
  67707. });
  67708. }
  67709. });
  67710. if (found === false) {
  67711. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  67712. }
  67713. }
  67714. }
  67715. // Material ?
  67716. if (parsedMesh.materialId) {
  67717. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  67718. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67719. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  67720. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  67721. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  67722. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  67723. var subMatId = parsedMultiMaterial.materials[matIndex];
  67724. loadedMaterialsIds.push(subMatId);
  67725. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  67726. if (mat) {
  67727. log += "\n\tMaterial " + mat.toString(fullDetails);
  67728. }
  67729. }
  67730. loadedMaterialsIds.push(parsedMultiMaterial.id);
  67731. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67732. if (mmat) {
  67733. materialFound = true;
  67734. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  67735. }
  67736. break;
  67737. }
  67738. }
  67739. }
  67740. if (materialFound === false) {
  67741. loadedMaterialsIds.push(parsedMesh.materialId);
  67742. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  67743. if (!mat) {
  67744. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  67745. }
  67746. else {
  67747. log += "\n\tMaterial " + mat.toString(fullDetails);
  67748. }
  67749. }
  67750. }
  67751. // Skeleton ?
  67752. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67753. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  67754. if (skeletonAlreadyLoaded === false) {
  67755. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  67756. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  67757. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  67758. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67759. skeletons.push(skeleton);
  67760. loadedSkeletonsIds.push(parsedSkeleton.id);
  67761. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  67762. }
  67763. }
  67764. }
  67765. }
  67766. // Morph targets ?
  67767. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67768. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67769. var managerData = _a[_i];
  67770. BABYLON.MorphTargetManager.Parse(managerData, scene);
  67771. }
  67772. }
  67773. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67774. meshes.push(mesh);
  67775. log += "\n\tMesh " + mesh.toString(fullDetails);
  67776. }
  67777. }
  67778. // Connecting parents
  67779. var currentMesh;
  67780. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67781. currentMesh = scene.meshes[index];
  67782. if (currentMesh._waitingParentId) {
  67783. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  67784. currentMesh._waitingParentId = null;
  67785. }
  67786. }
  67787. // freeze and compute world matrix application
  67788. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67789. currentMesh = scene.meshes[index];
  67790. if (currentMesh._waitingFreezeWorldMatrix) {
  67791. currentMesh.freezeWorldMatrix();
  67792. currentMesh._waitingFreezeWorldMatrix = null;
  67793. }
  67794. else {
  67795. currentMesh.computeWorldMatrix(true);
  67796. }
  67797. }
  67798. }
  67799. // Particles
  67800. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67801. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67802. var parsedParticleSystem = parsedData.particleSystems[index];
  67803. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  67804. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  67805. }
  67806. }
  67807. }
  67808. return true;
  67809. }
  67810. catch (err) {
  67811. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  67812. if (onError) {
  67813. onError(msg, err);
  67814. }
  67815. else {
  67816. BABYLON.Tools.Log(msg);
  67817. throw err;
  67818. }
  67819. }
  67820. finally {
  67821. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67822. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67823. }
  67824. }
  67825. return false;
  67826. },
  67827. load: function (scene, data, rootUrl, onError) {
  67828. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67829. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67830. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67831. // and avoid problems with multiple concurrent .babylon loads.
  67832. var log = "importScene has failed JSON parse";
  67833. try {
  67834. var parsedData = JSON.parse(data);
  67835. log = "";
  67836. // Scene
  67837. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  67838. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  67839. }
  67840. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  67841. scene.autoClear = parsedData.autoClear;
  67842. }
  67843. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  67844. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  67845. }
  67846. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  67847. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  67848. }
  67849. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  67850. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  67851. }
  67852. // Fog
  67853. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  67854. scene.fogMode = parsedData.fogMode;
  67855. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  67856. scene.fogStart = parsedData.fogStart;
  67857. scene.fogEnd = parsedData.fogEnd;
  67858. scene.fogDensity = parsedData.fogDensity;
  67859. log += "\tFog mode for scene: ";
  67860. switch (scene.fogMode) {
  67861. // getters not compiling, so using hardcoded
  67862. case 1:
  67863. log += "exp\n";
  67864. break;
  67865. case 2:
  67866. log += "exp2\n";
  67867. break;
  67868. case 3:
  67869. log += "linear\n";
  67870. break;
  67871. }
  67872. }
  67873. //Physics
  67874. if (parsedData.physicsEnabled) {
  67875. var physicsPlugin;
  67876. if (parsedData.physicsEngine === "cannon") {
  67877. physicsPlugin = new BABYLON.CannonJSPlugin();
  67878. }
  67879. else if (parsedData.physicsEngine === "oimo") {
  67880. physicsPlugin = new BABYLON.OimoJSPlugin();
  67881. }
  67882. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  67883. //else - default engine, which is currently oimo
  67884. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  67885. scene.enablePhysics(physicsGravity, physicsPlugin);
  67886. }
  67887. // Metadata
  67888. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  67889. scene.metadata = parsedData.metadata;
  67890. }
  67891. //collisions, if defined. otherwise, default is true
  67892. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  67893. scene.collisionsEnabled = parsedData.collisionsEnabled;
  67894. }
  67895. scene.workerCollisions = !!parsedData.workerCollisions;
  67896. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  67897. if (!container) {
  67898. return false;
  67899. }
  67900. if (parsedData.autoAnimate) {
  67901. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  67902. }
  67903. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  67904. scene.setActiveCameraByID(parsedData.activeCameraID);
  67905. }
  67906. // Environment texture
  67907. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  67908. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  67909. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  67910. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  67911. if (parsedData.environmentTextureRotationY) {
  67912. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  67913. }
  67914. scene.environmentTexture = hdrTexture;
  67915. }
  67916. else {
  67917. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  67918. if (parsedData.environmentTextureRotationY) {
  67919. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  67920. }
  67921. scene.environmentTexture = cubeTexture;
  67922. }
  67923. if (parsedData.createDefaultSkybox === true) {
  67924. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  67925. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  67926. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  67927. }
  67928. }
  67929. // Finish
  67930. return true;
  67931. }
  67932. catch (err) {
  67933. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  67934. if (onError) {
  67935. onError(msg, err);
  67936. }
  67937. else {
  67938. BABYLON.Tools.Log(msg);
  67939. throw err;
  67940. }
  67941. }
  67942. finally {
  67943. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67944. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67945. }
  67946. }
  67947. return false;
  67948. },
  67949. loadAssetContainer: function (scene, data, rootUrl, onError) {
  67950. var container = loadAssetContainer(scene, data, rootUrl, onError);
  67951. return container;
  67952. }
  67953. });
  67954. })(BABYLON || (BABYLON = {}));
  67955. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  67956. var BABYLON;
  67957. (function (BABYLON) {
  67958. var FilesInput = /** @class */ (function () {
  67959. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  67960. this.onProcessFileCallback = function () { return true; };
  67961. this._engine = engine;
  67962. this._currentScene = scene;
  67963. this._sceneLoadedCallback = sceneLoadedCallback;
  67964. this._progressCallback = progressCallback;
  67965. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  67966. this._textureLoadingCallback = textureLoadingCallback;
  67967. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  67968. this._onReloadCallback = onReloadCallback;
  67969. this._errorCallback = errorCallback;
  67970. }
  67971. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  67972. var _this = this;
  67973. if (elementToMonitor) {
  67974. this._elementToMonitor = elementToMonitor;
  67975. this._dragEnterHandler = function (e) { _this.drag(e); };
  67976. this._dragOverHandler = function (e) { _this.drag(e); };
  67977. this._dropHandler = function (e) { _this.drop(e); };
  67978. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  67979. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  67980. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  67981. }
  67982. };
  67983. FilesInput.prototype.dispose = function () {
  67984. if (!this._elementToMonitor) {
  67985. return;
  67986. }
  67987. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  67988. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  67989. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  67990. };
  67991. FilesInput.prototype.renderFunction = function () {
  67992. if (this._additionalRenderLoopLogicCallback) {
  67993. this._additionalRenderLoopLogicCallback();
  67994. }
  67995. if (this._currentScene) {
  67996. if (this._textureLoadingCallback) {
  67997. var remaining = this._currentScene.getWaitingItemsCount();
  67998. if (remaining > 0) {
  67999. this._textureLoadingCallback(remaining);
  68000. }
  68001. }
  68002. this._currentScene.render();
  68003. }
  68004. };
  68005. FilesInput.prototype.drag = function (e) {
  68006. e.stopPropagation();
  68007. e.preventDefault();
  68008. };
  68009. FilesInput.prototype.drop = function (eventDrop) {
  68010. eventDrop.stopPropagation();
  68011. eventDrop.preventDefault();
  68012. this.loadFiles(eventDrop);
  68013. };
  68014. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68015. var _this = this;
  68016. var reader = folder.createReader();
  68017. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68018. reader.readEntries(function (entries) {
  68019. remaining.count += entries.length;
  68020. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68021. var entry = entries_1[_i];
  68022. if (entry.isFile) {
  68023. entry.file(function (file) {
  68024. file.correctName = relativePath + file.name;
  68025. files.push(file);
  68026. if (--remaining.count === 0) {
  68027. callback();
  68028. }
  68029. });
  68030. }
  68031. else if (entry.isDirectory) {
  68032. _this._traverseFolder(entry, files, remaining, callback);
  68033. }
  68034. }
  68035. if (--remaining.count) {
  68036. callback();
  68037. }
  68038. });
  68039. };
  68040. FilesInput.prototype._processFiles = function (files) {
  68041. for (var i = 0; i < files.length; i++) {
  68042. var name = files[i].correctName.toLowerCase();
  68043. var extension = name.split('.').pop();
  68044. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68045. continue;
  68046. }
  68047. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68048. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68049. this._sceneFileToLoad = files[i];
  68050. }
  68051. else {
  68052. FilesInput.FilesToLoad[name] = files[i];
  68053. }
  68054. }
  68055. };
  68056. FilesInput.prototype.loadFiles = function (event) {
  68057. var _this = this;
  68058. if (this._startingProcessingFilesCallback)
  68059. this._startingProcessingFilesCallback();
  68060. // Handling data transfer via drag'n'drop
  68061. if (event && event.dataTransfer && event.dataTransfer.files) {
  68062. this._filesToLoad = event.dataTransfer.files;
  68063. }
  68064. // Handling files from input files
  68065. if (event && event.target && event.target.files) {
  68066. this._filesToLoad = event.target.files;
  68067. }
  68068. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68069. var files_1 = new Array();
  68070. var folders = [];
  68071. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68072. for (var i = 0; i < this._filesToLoad.length; i++) {
  68073. var fileToLoad = this._filesToLoad[i];
  68074. var name_1 = fileToLoad.name.toLowerCase();
  68075. var entry = void 0;
  68076. fileToLoad.correctName = name_1;
  68077. if (items) {
  68078. var item = items[i];
  68079. if (item.getAsEntry) {
  68080. entry = item.getAsEntry();
  68081. }
  68082. else if (item.webkitGetAsEntry) {
  68083. entry = item.webkitGetAsEntry();
  68084. }
  68085. }
  68086. if (!entry) {
  68087. files_1.push(fileToLoad);
  68088. }
  68089. else {
  68090. if (entry.isDirectory) {
  68091. folders.push(entry);
  68092. }
  68093. else {
  68094. files_1.push(fileToLoad);
  68095. }
  68096. }
  68097. }
  68098. if (folders.length === 0) {
  68099. this._processFiles(files_1);
  68100. this._processReload();
  68101. }
  68102. else {
  68103. var remaining = { count: folders.length };
  68104. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68105. var folder = folders_1[_i];
  68106. this._traverseFolder(folder, files_1, remaining, function () {
  68107. _this._processFiles(files_1);
  68108. if (remaining.count === 0) {
  68109. _this._processReload();
  68110. }
  68111. });
  68112. }
  68113. }
  68114. }
  68115. };
  68116. FilesInput.prototype._processReload = function () {
  68117. if (this._onReloadCallback) {
  68118. this._onReloadCallback(this._sceneFileToLoad);
  68119. }
  68120. else {
  68121. this.reload();
  68122. }
  68123. };
  68124. FilesInput.prototype.reload = function () {
  68125. var _this = this;
  68126. // If a scene file has been provided
  68127. if (this._sceneFileToLoad) {
  68128. if (this._currentScene) {
  68129. if (BABYLON.Tools.errorsCount > 0) {
  68130. BABYLON.Tools.ClearLogCache();
  68131. }
  68132. this._engine.stopRenderLoop();
  68133. }
  68134. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68135. if (_this._progressCallback) {
  68136. _this._progressCallback(progress);
  68137. }
  68138. }).then(function (scene) {
  68139. if (_this._currentScene) {
  68140. _this._currentScene.dispose();
  68141. }
  68142. _this._currentScene = scene;
  68143. if (_this._sceneLoadedCallback) {
  68144. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68145. }
  68146. // Wait for textures and shaders to be ready
  68147. _this._currentScene.executeWhenReady(function () {
  68148. _this._engine.runRenderLoop(function () {
  68149. _this.renderFunction();
  68150. });
  68151. });
  68152. }).catch(function (error) {
  68153. if (_this._errorCallback) {
  68154. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68155. }
  68156. });
  68157. }
  68158. else {
  68159. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68160. }
  68161. };
  68162. FilesInput.FilesToLoad = {};
  68163. return FilesInput;
  68164. }());
  68165. BABYLON.FilesInput = FilesInput;
  68166. })(BABYLON || (BABYLON = {}));
  68167. //# sourceMappingURL=babylon.filesInput.js.map
  68168. var BABYLON;
  68169. (function (BABYLON) {
  68170. /**
  68171. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68172. * The underlying implementation relies on an associative array to ensure the best performances.
  68173. * The value can be anything including 'null' but except 'undefined'
  68174. */
  68175. var StringDictionary = /** @class */ (function () {
  68176. function StringDictionary() {
  68177. this._count = 0;
  68178. this._data = {};
  68179. }
  68180. /**
  68181. * This will clear this dictionary and copy the content from the 'source' one.
  68182. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68183. * @param source the dictionary to take the content from and copy to this dictionary
  68184. */
  68185. StringDictionary.prototype.copyFrom = function (source) {
  68186. var _this = this;
  68187. this.clear();
  68188. source.forEach(function (t, v) { return _this.add(t, v); });
  68189. };
  68190. /**
  68191. * Get a value based from its key
  68192. * @param key the given key to get the matching value from
  68193. * @return the value if found, otherwise undefined is returned
  68194. */
  68195. StringDictionary.prototype.get = function (key) {
  68196. var val = this._data[key];
  68197. if (val !== undefined) {
  68198. return val;
  68199. }
  68200. return undefined;
  68201. };
  68202. /**
  68203. * Get a value from its key or add it if it doesn't exist.
  68204. * This method will ensure you that a given key/data will be present in the dictionary.
  68205. * @param key the given key to get the matching value from
  68206. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68207. * The factory will only be invoked if there's no data for the given key.
  68208. * @return the value corresponding to the key.
  68209. */
  68210. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68211. var val = this.get(key);
  68212. if (val !== undefined) {
  68213. return val;
  68214. }
  68215. val = factory(key);
  68216. if (val) {
  68217. this.add(key, val);
  68218. }
  68219. return val;
  68220. };
  68221. /**
  68222. * Get a value from its key if present in the dictionary otherwise add it
  68223. * @param key the key to get the value from
  68224. * @param val if there's no such key/value pair in the dictionary add it with this value
  68225. * @return the value corresponding to the key
  68226. */
  68227. StringDictionary.prototype.getOrAdd = function (key, val) {
  68228. var curVal = this.get(key);
  68229. if (curVal !== undefined) {
  68230. return curVal;
  68231. }
  68232. this.add(key, val);
  68233. return val;
  68234. };
  68235. /**
  68236. * Check if there's a given key in the dictionary
  68237. * @param key the key to check for
  68238. * @return true if the key is present, false otherwise
  68239. */
  68240. StringDictionary.prototype.contains = function (key) {
  68241. return this._data[key] !== undefined;
  68242. };
  68243. /**
  68244. * Add a new key and its corresponding value
  68245. * @param key the key to add
  68246. * @param value the value corresponding to the key
  68247. * @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
  68248. */
  68249. StringDictionary.prototype.add = function (key, value) {
  68250. if (this._data[key] !== undefined) {
  68251. return false;
  68252. }
  68253. this._data[key] = value;
  68254. ++this._count;
  68255. return true;
  68256. };
  68257. StringDictionary.prototype.set = function (key, value) {
  68258. if (this._data[key] === undefined) {
  68259. return false;
  68260. }
  68261. this._data[key] = value;
  68262. return true;
  68263. };
  68264. /**
  68265. * Get the element of the given key and remove it from the dictionary
  68266. * @param key
  68267. */
  68268. StringDictionary.prototype.getAndRemove = function (key) {
  68269. var val = this.get(key);
  68270. if (val !== undefined) {
  68271. delete this._data[key];
  68272. --this._count;
  68273. return val;
  68274. }
  68275. return null;
  68276. };
  68277. /**
  68278. * Remove a key/value from the dictionary.
  68279. * @param key the key to remove
  68280. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68281. */
  68282. StringDictionary.prototype.remove = function (key) {
  68283. if (this.contains(key)) {
  68284. delete this._data[key];
  68285. --this._count;
  68286. return true;
  68287. }
  68288. return false;
  68289. };
  68290. /**
  68291. * Clear the whole content of the dictionary
  68292. */
  68293. StringDictionary.prototype.clear = function () {
  68294. this._data = {};
  68295. this._count = 0;
  68296. };
  68297. Object.defineProperty(StringDictionary.prototype, "count", {
  68298. get: function () {
  68299. return this._count;
  68300. },
  68301. enumerable: true,
  68302. configurable: true
  68303. });
  68304. /**
  68305. * Execute a callback on each key/val of the dictionary.
  68306. * Note that you can remove any element in this dictionary in the callback implementation
  68307. * @param callback the callback to execute on a given key/value pair
  68308. */
  68309. StringDictionary.prototype.forEach = function (callback) {
  68310. for (var cur in this._data) {
  68311. var val = this._data[cur];
  68312. callback(cur, val);
  68313. }
  68314. };
  68315. /**
  68316. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68317. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68318. * Note that you can remove any element in this dictionary in the callback implementation
  68319. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68320. */
  68321. StringDictionary.prototype.first = function (callback) {
  68322. for (var cur in this._data) {
  68323. var val = this._data[cur];
  68324. var res = callback(cur, val);
  68325. if (res) {
  68326. return res;
  68327. }
  68328. }
  68329. return null;
  68330. };
  68331. return StringDictionary;
  68332. }());
  68333. BABYLON.StringDictionary = StringDictionary;
  68334. })(BABYLON || (BABYLON = {}));
  68335. //# sourceMappingURL=babylon.stringDictionary.js.map
  68336. var BABYLON;
  68337. (function (BABYLON) {
  68338. var Tags = /** @class */ (function () {
  68339. function Tags() {
  68340. }
  68341. Tags.EnableFor = function (obj) {
  68342. obj._tags = obj._tags || {};
  68343. obj.hasTags = function () {
  68344. return Tags.HasTags(obj);
  68345. };
  68346. obj.addTags = function (tagsString) {
  68347. return Tags.AddTagsTo(obj, tagsString);
  68348. };
  68349. obj.removeTags = function (tagsString) {
  68350. return Tags.RemoveTagsFrom(obj, tagsString);
  68351. };
  68352. obj.matchesTagsQuery = function (tagsQuery) {
  68353. return Tags.MatchesQuery(obj, tagsQuery);
  68354. };
  68355. };
  68356. Tags.DisableFor = function (obj) {
  68357. delete obj._tags;
  68358. delete obj.hasTags;
  68359. delete obj.addTags;
  68360. delete obj.removeTags;
  68361. delete obj.matchesTagsQuery;
  68362. };
  68363. Tags.HasTags = function (obj) {
  68364. if (!obj._tags) {
  68365. return false;
  68366. }
  68367. return !BABYLON.Tools.IsEmpty(obj._tags);
  68368. };
  68369. Tags.GetTags = function (obj, asString) {
  68370. if (asString === void 0) { asString = true; }
  68371. if (!obj._tags) {
  68372. return null;
  68373. }
  68374. if (asString) {
  68375. var tagsArray = [];
  68376. for (var tag in obj._tags) {
  68377. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68378. tagsArray.push(tag);
  68379. }
  68380. }
  68381. return tagsArray.join(" ");
  68382. }
  68383. else {
  68384. return obj._tags;
  68385. }
  68386. };
  68387. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68388. // a tag cannot start with '||', '&&', and '!'
  68389. // it cannot contain whitespaces
  68390. Tags.AddTagsTo = function (obj, tagsString) {
  68391. if (!tagsString) {
  68392. return;
  68393. }
  68394. if (typeof tagsString !== "string") {
  68395. return;
  68396. }
  68397. var tags = tagsString.split(" ");
  68398. tags.forEach(function (tag, index, array) {
  68399. Tags._AddTagTo(obj, tag);
  68400. });
  68401. };
  68402. Tags._AddTagTo = function (obj, tag) {
  68403. tag = tag.trim();
  68404. if (tag === "" || tag === "true" || tag === "false") {
  68405. return;
  68406. }
  68407. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  68408. return;
  68409. }
  68410. Tags.EnableFor(obj);
  68411. obj._tags[tag] = true;
  68412. };
  68413. Tags.RemoveTagsFrom = function (obj, tagsString) {
  68414. if (!Tags.HasTags(obj)) {
  68415. return;
  68416. }
  68417. var tags = tagsString.split(" ");
  68418. for (var t in tags) {
  68419. Tags._RemoveTagFrom(obj, tags[t]);
  68420. }
  68421. };
  68422. Tags._RemoveTagFrom = function (obj, tag) {
  68423. delete obj._tags[tag];
  68424. };
  68425. Tags.MatchesQuery = function (obj, tagsQuery) {
  68426. if (tagsQuery === undefined) {
  68427. return true;
  68428. }
  68429. if (tagsQuery === "") {
  68430. return Tags.HasTags(obj);
  68431. }
  68432. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  68433. };
  68434. return Tags;
  68435. }());
  68436. BABYLON.Tags = Tags;
  68437. })(BABYLON || (BABYLON = {}));
  68438. //# sourceMappingURL=babylon.tags.js.map
  68439. var BABYLON;
  68440. (function (BABYLON) {
  68441. /**
  68442. * Class used to evalaute queries containing `and` and `or` operators
  68443. */
  68444. var AndOrNotEvaluator = /** @class */ (function () {
  68445. function AndOrNotEvaluator() {
  68446. }
  68447. /**
  68448. * Evaluate a query
  68449. * @param query defines the query to evaluate
  68450. * @param evaluateCallback defines the callback used to filter result
  68451. * @returns true if the query matches
  68452. */
  68453. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  68454. if (!query.match(/\([^\(\)]*\)/g)) {
  68455. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  68456. }
  68457. else {
  68458. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  68459. // remove parenthesis
  68460. r = r.slice(1, r.length - 1);
  68461. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  68462. });
  68463. }
  68464. if (query === "true") {
  68465. return true;
  68466. }
  68467. if (query === "false") {
  68468. return false;
  68469. }
  68470. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  68471. };
  68472. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  68473. evaluateCallback = evaluateCallback || (function (r) {
  68474. return r === "true" ? true : false;
  68475. });
  68476. var result;
  68477. var or = parenthesisContent.split("||");
  68478. for (var i in or) {
  68479. if (or.hasOwnProperty(i)) {
  68480. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  68481. var and = ori.split("&&");
  68482. if (and.length > 1) {
  68483. for (var j = 0; j < and.length; ++j) {
  68484. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  68485. if (andj !== "true" && andj !== "false") {
  68486. if (andj[0] === "!") {
  68487. result = !evaluateCallback(andj.substring(1));
  68488. }
  68489. else {
  68490. result = evaluateCallback(andj);
  68491. }
  68492. }
  68493. else {
  68494. result = andj === "true" ? true : false;
  68495. }
  68496. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  68497. ori = "false";
  68498. break;
  68499. }
  68500. }
  68501. }
  68502. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  68503. result = true;
  68504. break;
  68505. }
  68506. // result equals false (or undefined)
  68507. if (ori !== "true" && ori !== "false") {
  68508. if (ori[0] === "!") {
  68509. result = !evaluateCallback(ori.substring(1));
  68510. }
  68511. else {
  68512. result = evaluateCallback(ori);
  68513. }
  68514. }
  68515. else {
  68516. result = ori === "true" ? true : false;
  68517. }
  68518. }
  68519. }
  68520. // the whole parenthesis scope is replaced by 'true' or 'false'
  68521. return result ? "true" : "false";
  68522. };
  68523. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  68524. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  68525. // remove whitespaces
  68526. r = r.replace(/[\s]/g, function () { return ""; });
  68527. return r.length % 2 ? "!" : "";
  68528. });
  68529. booleanString = booleanString.trim();
  68530. if (booleanString === "!true") {
  68531. booleanString = "false";
  68532. }
  68533. else if (booleanString === "!false") {
  68534. booleanString = "true";
  68535. }
  68536. return booleanString;
  68537. };
  68538. return AndOrNotEvaluator;
  68539. }());
  68540. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  68541. })(BABYLON || (BABYLON = {}));
  68542. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  68543. var BABYLON;
  68544. (function (BABYLON) {
  68545. /**
  68546. * Class used to enable access to IndexedDB
  68547. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  68548. */
  68549. var Database = /** @class */ (function () {
  68550. /**
  68551. * Creates a new Database
  68552. * @param urlToScene defines the url to load the scene
  68553. * @param callbackManifestChecked defines the callback to use when manifest is checked
  68554. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  68555. */
  68556. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  68557. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  68558. var _this = this;
  68559. // Handling various flavors of prefixed version of IndexedDB
  68560. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  68561. this.callbackManifestChecked = callbackManifestChecked;
  68562. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  68563. this.db = null;
  68564. this._enableSceneOffline = false;
  68565. this._enableTexturesOffline = false;
  68566. this.manifestVersionFound = 0;
  68567. this.mustUpdateRessources = false;
  68568. this.hasReachedQuota = false;
  68569. if (!Database.IDBStorageEnabled) {
  68570. this.callbackManifestChecked(true);
  68571. }
  68572. else {
  68573. if (disableManifestCheck) {
  68574. this._enableSceneOffline = true;
  68575. this._enableTexturesOffline = true;
  68576. this.manifestVersionFound = 1;
  68577. BABYLON.Tools.SetImmediate(function () {
  68578. _this.callbackManifestChecked(true);
  68579. });
  68580. }
  68581. else {
  68582. this._checkManifestFile();
  68583. }
  68584. }
  68585. }
  68586. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  68587. /**
  68588. * Gets a boolean indicating if scene must be saved in the database
  68589. */
  68590. get: function () {
  68591. return this._enableSceneOffline;
  68592. },
  68593. enumerable: true,
  68594. configurable: true
  68595. });
  68596. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  68597. /**
  68598. * Gets a boolean indicating if textures must be saved in the database
  68599. */
  68600. get: function () {
  68601. return this._enableTexturesOffline;
  68602. },
  68603. enumerable: true,
  68604. configurable: true
  68605. });
  68606. Database.prototype._checkManifestFile = function () {
  68607. var _this = this;
  68608. var noManifestFile = function () {
  68609. _this._enableSceneOffline = false;
  68610. _this._enableTexturesOffline = false;
  68611. _this.callbackManifestChecked(false);
  68612. };
  68613. var timeStampUsed = false;
  68614. var manifestURL = this.currentSceneUrl + ".manifest";
  68615. var xhr = new XMLHttpRequest();
  68616. if (navigator.onLine) {
  68617. // Adding a timestamp to by-pass browsers' cache
  68618. timeStampUsed = true;
  68619. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  68620. }
  68621. xhr.open("GET", manifestURL, true);
  68622. xhr.addEventListener("load", function () {
  68623. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68624. try {
  68625. var manifestFile = JSON.parse(xhr.response);
  68626. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  68627. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  68628. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  68629. _this.manifestVersionFound = manifestFile.version;
  68630. }
  68631. if (_this.callbackManifestChecked) {
  68632. _this.callbackManifestChecked(true);
  68633. }
  68634. }
  68635. catch (ex) {
  68636. noManifestFile();
  68637. }
  68638. }
  68639. else {
  68640. noManifestFile();
  68641. }
  68642. }, false);
  68643. xhr.addEventListener("error", function (event) {
  68644. if (timeStampUsed) {
  68645. timeStampUsed = false;
  68646. // Let's retry without the timeStamp
  68647. // It could fail when coupled with HTML5 Offline API
  68648. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  68649. xhr.open("GET", retryManifestURL, true);
  68650. xhr.send();
  68651. }
  68652. else {
  68653. noManifestFile();
  68654. }
  68655. }, false);
  68656. try {
  68657. xhr.send();
  68658. }
  68659. catch (ex) {
  68660. BABYLON.Tools.Error("Error on XHR send request.");
  68661. this.callbackManifestChecked(false);
  68662. }
  68663. };
  68664. /**
  68665. * Open the database and make it available
  68666. * @param successCallback defines the callback to call on success
  68667. * @param errorCallback defines the callback to call on error
  68668. */
  68669. Database.prototype.openAsync = function (successCallback, errorCallback) {
  68670. var _this = this;
  68671. var handleError = function () {
  68672. _this.isSupported = false;
  68673. if (errorCallback)
  68674. errorCallback();
  68675. };
  68676. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  68677. // Your browser doesn't support IndexedDB
  68678. this.isSupported = false;
  68679. if (errorCallback)
  68680. errorCallback();
  68681. }
  68682. else {
  68683. // If the DB hasn't been opened or created yet
  68684. if (!this.db) {
  68685. this.hasReachedQuota = false;
  68686. this.isSupported = true;
  68687. var request = this.idbFactory.open("babylonjs", 1);
  68688. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  68689. request.onerror = function (event) {
  68690. handleError();
  68691. };
  68692. // executes when a version change transaction cannot complete due to other active transactions
  68693. request.onblocked = function (event) {
  68694. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  68695. handleError();
  68696. };
  68697. // DB has been opened successfully
  68698. request.onsuccess = function (event) {
  68699. _this.db = request.result;
  68700. successCallback();
  68701. };
  68702. // Initialization of the DB. Creating Scenes & Textures stores
  68703. request.onupgradeneeded = function (event) {
  68704. _this.db = (event.target).result;
  68705. if (_this.db) {
  68706. try {
  68707. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  68708. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  68709. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  68710. }
  68711. catch (ex) {
  68712. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  68713. handleError();
  68714. }
  68715. }
  68716. };
  68717. }
  68718. // DB has already been created and opened
  68719. else {
  68720. if (successCallback)
  68721. successCallback();
  68722. }
  68723. }
  68724. };
  68725. /**
  68726. * Loads an image from the database
  68727. * @param url defines the url to load from
  68728. * @param image defines the target DOM image
  68729. */
  68730. Database.prototype.loadImageFromDB = function (url, image) {
  68731. var _this = this;
  68732. var completeURL = Database._ReturnFullUrlLocation(url);
  68733. var saveAndLoadImage = function () {
  68734. if (!_this.hasReachedQuota && _this.db !== null) {
  68735. // the texture is not yet in the DB, let's try to save it
  68736. _this._saveImageIntoDBAsync(completeURL, image);
  68737. }
  68738. // If the texture is not in the DB and we've reached the DB quota limit
  68739. // let's load it directly from the web
  68740. else {
  68741. image.src = url;
  68742. }
  68743. };
  68744. if (!this.mustUpdateRessources) {
  68745. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  68746. }
  68747. // First time we're download the images or update requested in the manifest file by a version change
  68748. else {
  68749. saveAndLoadImage();
  68750. }
  68751. };
  68752. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  68753. if (this.isSupported && this.db !== null) {
  68754. var texture;
  68755. var transaction = this.db.transaction(["textures"]);
  68756. transaction.onabort = function (event) {
  68757. image.src = url;
  68758. };
  68759. transaction.oncomplete = function (event) {
  68760. var blobTextureURL;
  68761. if (texture) {
  68762. var URL = window.URL || window.webkitURL;
  68763. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  68764. image.onerror = function () {
  68765. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  68766. image.src = url;
  68767. };
  68768. image.src = blobTextureURL;
  68769. }
  68770. else {
  68771. notInDBCallback();
  68772. }
  68773. };
  68774. var getRequest = transaction.objectStore("textures").get(url);
  68775. getRequest.onsuccess = function (event) {
  68776. texture = (event.target).result;
  68777. };
  68778. getRequest.onerror = function (event) {
  68779. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  68780. image.src = url;
  68781. };
  68782. }
  68783. else {
  68784. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68785. image.src = url;
  68786. }
  68787. };
  68788. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  68789. var _this = this;
  68790. if (this.isSupported) {
  68791. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  68792. var generateBlobUrl = function () {
  68793. var blobTextureURL;
  68794. if (blob) {
  68795. var URL = window.URL || window.webkitURL;
  68796. try {
  68797. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  68798. }
  68799. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  68800. catch (ex) {
  68801. blobTextureURL = URL.createObjectURL(blob);
  68802. }
  68803. }
  68804. if (blobTextureURL) {
  68805. image.src = blobTextureURL;
  68806. }
  68807. };
  68808. if (Database.IsUASupportingBlobStorage) { // Create XHR
  68809. var xhr = new XMLHttpRequest(), blob;
  68810. xhr.open("GET", url, true);
  68811. xhr.responseType = "blob";
  68812. xhr.addEventListener("load", function () {
  68813. if (xhr.status === 200 && _this.db) {
  68814. // Blob as response (XHR2)
  68815. blob = xhr.response;
  68816. var transaction = _this.db.transaction(["textures"], "readwrite");
  68817. // the transaction could abort because of a QuotaExceededError error
  68818. transaction.onabort = function (event) {
  68819. try {
  68820. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68821. var srcElement = (event.srcElement || event.target);
  68822. var error = srcElement.error;
  68823. if (error && error.name === "QuotaExceededError") {
  68824. _this.hasReachedQuota = true;
  68825. }
  68826. }
  68827. catch (ex) { }
  68828. generateBlobUrl();
  68829. };
  68830. transaction.oncomplete = function (event) {
  68831. generateBlobUrl();
  68832. };
  68833. var newTexture = { textureUrl: url, data: blob };
  68834. try {
  68835. // Put the blob into the dabase
  68836. var addRequest = transaction.objectStore("textures").put(newTexture);
  68837. addRequest.onsuccess = function (event) {
  68838. };
  68839. addRequest.onerror = function (event) {
  68840. generateBlobUrl();
  68841. };
  68842. }
  68843. catch (ex) {
  68844. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  68845. if (ex.code === 25) {
  68846. Database.IsUASupportingBlobStorage = false;
  68847. }
  68848. image.src = url;
  68849. }
  68850. }
  68851. else {
  68852. image.src = url;
  68853. }
  68854. }, false);
  68855. xhr.addEventListener("error", function (event) {
  68856. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  68857. image.src = url;
  68858. }, false);
  68859. xhr.send();
  68860. }
  68861. else {
  68862. image.src = url;
  68863. }
  68864. }
  68865. else {
  68866. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68867. image.src = url;
  68868. }
  68869. };
  68870. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  68871. var _this = this;
  68872. var updateVersion = function () {
  68873. // the version is not yet in the DB or we need to update it
  68874. _this._saveVersionIntoDBAsync(url, versionLoaded);
  68875. };
  68876. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  68877. };
  68878. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  68879. var _this = this;
  68880. if (this.isSupported && this.db) {
  68881. var version;
  68882. try {
  68883. var transaction = this.db.transaction(["versions"]);
  68884. transaction.oncomplete = function (event) {
  68885. if (version) {
  68886. // If the version in the JSON file is different from the version in DB
  68887. if (_this.manifestVersionFound !== version.data) {
  68888. _this.mustUpdateRessources = true;
  68889. updateInDBCallback();
  68890. }
  68891. else {
  68892. callback(version.data);
  68893. }
  68894. }
  68895. // version was not found in DB
  68896. else {
  68897. _this.mustUpdateRessources = true;
  68898. updateInDBCallback();
  68899. }
  68900. };
  68901. transaction.onabort = function (event) {
  68902. callback(-1);
  68903. };
  68904. var getRequest = transaction.objectStore("versions").get(url);
  68905. getRequest.onsuccess = function (event) {
  68906. version = (event.target).result;
  68907. };
  68908. getRequest.onerror = function (event) {
  68909. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  68910. callback(-1);
  68911. };
  68912. }
  68913. catch (ex) {
  68914. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  68915. callback(-1);
  68916. }
  68917. }
  68918. else {
  68919. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68920. callback(-1);
  68921. }
  68922. };
  68923. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  68924. var _this = this;
  68925. if (this.isSupported && !this.hasReachedQuota && this.db) {
  68926. try {
  68927. // Open a transaction to the database
  68928. var transaction = this.db.transaction(["versions"], "readwrite");
  68929. // the transaction could abort because of a QuotaExceededError error
  68930. transaction.onabort = function (event) {
  68931. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68932. var error = event.srcElement['error'];
  68933. if (error && error.name === "QuotaExceededError") {
  68934. _this.hasReachedQuota = true;
  68935. }
  68936. }
  68937. catch (ex) { }
  68938. callback(-1);
  68939. };
  68940. transaction.oncomplete = function (event) {
  68941. callback(_this.manifestVersionFound);
  68942. };
  68943. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  68944. // Put the scene into the database
  68945. var addRequest = transaction.objectStore("versions").put(newVersion);
  68946. addRequest.onsuccess = function (event) {
  68947. };
  68948. addRequest.onerror = function (event) {
  68949. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  68950. };
  68951. }
  68952. catch (ex) {
  68953. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  68954. callback(-1);
  68955. }
  68956. }
  68957. else {
  68958. callback(-1);
  68959. }
  68960. };
  68961. /**
  68962. * Loads a file from database
  68963. * @param url defines the URL to load from
  68964. * @param sceneLoaded defines a callback to call on success
  68965. * @param progressCallBack defines a callback to call when progress changed
  68966. * @param errorCallback defines a callback to call on error
  68967. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  68968. */
  68969. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  68970. var _this = this;
  68971. var completeUrl = Database._ReturnFullUrlLocation(url);
  68972. var saveAndLoadFile = function () {
  68973. // the scene is not yet in the DB, let's try to save it
  68974. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  68975. };
  68976. this._checkVersionFromDB(completeUrl, function (version) {
  68977. if (version !== -1) {
  68978. if (!_this.mustUpdateRessources) {
  68979. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  68980. }
  68981. else {
  68982. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  68983. }
  68984. }
  68985. else {
  68986. if (errorCallback) {
  68987. errorCallback();
  68988. }
  68989. }
  68990. });
  68991. };
  68992. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  68993. if (this.isSupported && this.db) {
  68994. var targetStore;
  68995. if (url.indexOf(".babylon") !== -1) {
  68996. targetStore = "scenes";
  68997. }
  68998. else {
  68999. targetStore = "textures";
  69000. }
  69001. var file;
  69002. var transaction = this.db.transaction([targetStore]);
  69003. transaction.oncomplete = function (event) {
  69004. if (file) {
  69005. callback(file.data);
  69006. }
  69007. // file was not found in DB
  69008. else {
  69009. notInDBCallback();
  69010. }
  69011. };
  69012. transaction.onabort = function (event) {
  69013. notInDBCallback();
  69014. };
  69015. var getRequest = transaction.objectStore(targetStore).get(url);
  69016. getRequest.onsuccess = function (event) {
  69017. file = (event.target).result;
  69018. };
  69019. getRequest.onerror = function (event) {
  69020. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69021. notInDBCallback();
  69022. };
  69023. }
  69024. else {
  69025. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69026. callback();
  69027. }
  69028. };
  69029. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69030. var _this = this;
  69031. if (this.isSupported) {
  69032. var targetStore;
  69033. if (url.indexOf(".babylon") !== -1) {
  69034. targetStore = "scenes";
  69035. }
  69036. else {
  69037. targetStore = "textures";
  69038. }
  69039. // Create XHR
  69040. var xhr = new XMLHttpRequest();
  69041. var fileData;
  69042. xhr.open("GET", url, true);
  69043. if (useArrayBuffer) {
  69044. xhr.responseType = "arraybuffer";
  69045. }
  69046. if (progressCallback) {
  69047. xhr.onprogress = progressCallback;
  69048. }
  69049. xhr.addEventListener("load", function () {
  69050. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69051. // Blob as response (XHR2)
  69052. //fileData = xhr.responseText;
  69053. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69054. if (!_this.hasReachedQuota && _this.db) {
  69055. // Open a transaction to the database
  69056. var transaction = _this.db.transaction([targetStore], "readwrite");
  69057. // the transaction could abort because of a QuotaExceededError error
  69058. transaction.onabort = function (event) {
  69059. try {
  69060. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69061. var error = event.srcElement['error'];
  69062. if (error && error.name === "QuotaExceededError") {
  69063. _this.hasReachedQuota = true;
  69064. }
  69065. }
  69066. catch (ex) { }
  69067. callback(fileData);
  69068. };
  69069. transaction.oncomplete = function (event) {
  69070. callback(fileData);
  69071. };
  69072. var newFile;
  69073. if (targetStore === "scenes") {
  69074. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69075. }
  69076. else {
  69077. newFile = { textureUrl: url, data: fileData };
  69078. }
  69079. try {
  69080. // Put the scene into the database
  69081. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69082. addRequest.onsuccess = function (event) {
  69083. };
  69084. addRequest.onerror = function (event) {
  69085. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69086. };
  69087. }
  69088. catch (ex) {
  69089. callback(fileData);
  69090. }
  69091. }
  69092. else {
  69093. callback(fileData);
  69094. }
  69095. }
  69096. else {
  69097. callback();
  69098. }
  69099. }, false);
  69100. xhr.addEventListener("error", function (event) {
  69101. BABYLON.Tools.Error("error on XHR request.");
  69102. callback();
  69103. }, false);
  69104. xhr.send();
  69105. }
  69106. else {
  69107. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69108. callback();
  69109. }
  69110. };
  69111. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69112. Database.IsUASupportingBlobStorage = true;
  69113. /** Gets a boolean indicating if Database storate is enabled */
  69114. Database.IDBStorageEnabled = true;
  69115. Database._ParseURL = function (url) {
  69116. var a = document.createElement('a');
  69117. a.href = url;
  69118. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69119. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69120. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69121. return absLocation;
  69122. };
  69123. Database._ReturnFullUrlLocation = function (url) {
  69124. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69125. return (Database._ParseURL(window.location.href) + url);
  69126. }
  69127. else {
  69128. return url;
  69129. }
  69130. };
  69131. return Database;
  69132. }());
  69133. BABYLON.Database = Database;
  69134. })(BABYLON || (BABYLON = {}));
  69135. //# sourceMappingURL=babylon.database.js.map
  69136. var BABYLON;
  69137. (function (BABYLON) {
  69138. var FresnelParameters = /** @class */ (function () {
  69139. function FresnelParameters() {
  69140. this._isEnabled = true;
  69141. this.leftColor = BABYLON.Color3.White();
  69142. this.rightColor = BABYLON.Color3.Black();
  69143. this.bias = 0;
  69144. this.power = 1;
  69145. }
  69146. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69147. get: function () {
  69148. return this._isEnabled;
  69149. },
  69150. set: function (value) {
  69151. if (this._isEnabled === value) {
  69152. return;
  69153. }
  69154. this._isEnabled = value;
  69155. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69156. },
  69157. enumerable: true,
  69158. configurable: true
  69159. });
  69160. FresnelParameters.prototype.clone = function () {
  69161. var newFresnelParameters = new FresnelParameters();
  69162. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69163. return newFresnelParameters;
  69164. };
  69165. FresnelParameters.prototype.serialize = function () {
  69166. var serializationObject = {};
  69167. serializationObject.isEnabled = this.isEnabled;
  69168. serializationObject.leftColor = this.leftColor.asArray();
  69169. serializationObject.rightColor = this.rightColor.asArray();
  69170. serializationObject.bias = this.bias;
  69171. serializationObject.power = this.power;
  69172. return serializationObject;
  69173. };
  69174. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69175. var fresnelParameters = new FresnelParameters();
  69176. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69177. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69178. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69179. fresnelParameters.bias = parsedFresnelParameters.bias;
  69180. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69181. return fresnelParameters;
  69182. };
  69183. return FresnelParameters;
  69184. }());
  69185. BABYLON.FresnelParameters = FresnelParameters;
  69186. })(BABYLON || (BABYLON = {}));
  69187. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69188. var BABYLON;
  69189. (function (BABYLON) {
  69190. var MultiMaterial = /** @class */ (function (_super) {
  69191. __extends(MultiMaterial, _super);
  69192. function MultiMaterial(name, scene) {
  69193. var _this = _super.call(this, name, scene, true) || this;
  69194. scene.multiMaterials.push(_this);
  69195. _this.subMaterials = new Array();
  69196. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69197. return _this;
  69198. }
  69199. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69200. get: function () {
  69201. return this._subMaterials;
  69202. },
  69203. set: function (value) {
  69204. this._subMaterials = value;
  69205. this._hookArray(value);
  69206. },
  69207. enumerable: true,
  69208. configurable: true
  69209. });
  69210. MultiMaterial.prototype._hookArray = function (array) {
  69211. var _this = this;
  69212. var oldPush = array.push;
  69213. array.push = function () {
  69214. var items = [];
  69215. for (var _i = 0; _i < arguments.length; _i++) {
  69216. items[_i] = arguments[_i];
  69217. }
  69218. var result = oldPush.apply(array, items);
  69219. _this._markAllSubMeshesAsTexturesDirty();
  69220. return result;
  69221. };
  69222. var oldSplice = array.splice;
  69223. array.splice = function (index, deleteCount) {
  69224. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69225. _this._markAllSubMeshesAsTexturesDirty();
  69226. return deleted;
  69227. };
  69228. };
  69229. // Properties
  69230. MultiMaterial.prototype.getSubMaterial = function (index) {
  69231. if (index < 0 || index >= this.subMaterials.length) {
  69232. return this.getScene().defaultMaterial;
  69233. }
  69234. return this.subMaterials[index];
  69235. };
  69236. MultiMaterial.prototype.getActiveTextures = function () {
  69237. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69238. if (subMaterial) {
  69239. return subMaterial.getActiveTextures();
  69240. }
  69241. else {
  69242. return [];
  69243. }
  69244. }));
  69245. var _a;
  69246. };
  69247. // Methods
  69248. MultiMaterial.prototype.getClassName = function () {
  69249. return "MultiMaterial";
  69250. };
  69251. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69252. for (var index = 0; index < this.subMaterials.length; index++) {
  69253. var subMaterial = this.subMaterials[index];
  69254. if (subMaterial) {
  69255. if (subMaterial.storeEffectOnSubMeshes) {
  69256. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69257. return false;
  69258. }
  69259. continue;
  69260. }
  69261. if (!subMaterial.isReady(mesh)) {
  69262. return false;
  69263. }
  69264. }
  69265. }
  69266. return true;
  69267. };
  69268. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69269. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69270. for (var index = 0; index < this.subMaterials.length; index++) {
  69271. var subMaterial = null;
  69272. var current = this.subMaterials[index];
  69273. if (cloneChildren && current) {
  69274. subMaterial = current.clone(name + "-" + current.name);
  69275. }
  69276. else {
  69277. subMaterial = this.subMaterials[index];
  69278. }
  69279. newMultiMaterial.subMaterials.push(subMaterial);
  69280. }
  69281. return newMultiMaterial;
  69282. };
  69283. MultiMaterial.prototype.serialize = function () {
  69284. var serializationObject = {};
  69285. serializationObject.name = this.name;
  69286. serializationObject.id = this.id;
  69287. if (BABYLON.Tags) {
  69288. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69289. }
  69290. serializationObject.materials = [];
  69291. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69292. var subMat = this.subMaterials[matIndex];
  69293. if (subMat) {
  69294. serializationObject.materials.push(subMat.id);
  69295. }
  69296. else {
  69297. serializationObject.materials.push(null);
  69298. }
  69299. }
  69300. return serializationObject;
  69301. };
  69302. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69303. var scene = this.getScene();
  69304. if (!scene) {
  69305. return;
  69306. }
  69307. var index = scene.multiMaterials.indexOf(this);
  69308. if (index >= 0) {
  69309. scene.multiMaterials.splice(index, 1);
  69310. }
  69311. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69312. };
  69313. return MultiMaterial;
  69314. }(BABYLON.Material));
  69315. BABYLON.MultiMaterial = MultiMaterial;
  69316. })(BABYLON || (BABYLON = {}));
  69317. //# sourceMappingURL=babylon.multiMaterial.js.map
  69318. var BABYLON;
  69319. (function (BABYLON) {
  69320. var FreeCameraTouchInput = /** @class */ (function () {
  69321. function FreeCameraTouchInput() {
  69322. this._offsetX = null;
  69323. this._offsetY = null;
  69324. this._pointerPressed = new Array();
  69325. this.touchAngularSensibility = 200000.0;
  69326. this.touchMoveSensibility = 250.0;
  69327. }
  69328. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69329. var _this = this;
  69330. var previousPosition = null;
  69331. if (this._pointerInput === undefined) {
  69332. this._onLostFocus = function (evt) {
  69333. _this._offsetX = null;
  69334. _this._offsetY = null;
  69335. };
  69336. this._pointerInput = function (p, s) {
  69337. var evt = p.event;
  69338. if (evt.pointerType === "mouse") {
  69339. return;
  69340. }
  69341. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69342. if (!noPreventDefault) {
  69343. evt.preventDefault();
  69344. }
  69345. _this._pointerPressed.push(evt.pointerId);
  69346. if (_this._pointerPressed.length !== 1) {
  69347. return;
  69348. }
  69349. previousPosition = {
  69350. x: evt.clientX,
  69351. y: evt.clientY
  69352. };
  69353. }
  69354. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69355. if (!noPreventDefault) {
  69356. evt.preventDefault();
  69357. }
  69358. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69359. if (index === -1) {
  69360. return;
  69361. }
  69362. _this._pointerPressed.splice(index, 1);
  69363. if (index != 0) {
  69364. return;
  69365. }
  69366. previousPosition = null;
  69367. _this._offsetX = null;
  69368. _this._offsetY = null;
  69369. }
  69370. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69371. if (!noPreventDefault) {
  69372. evt.preventDefault();
  69373. }
  69374. if (!previousPosition) {
  69375. return;
  69376. }
  69377. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69378. if (index != 0) {
  69379. return;
  69380. }
  69381. _this._offsetX = evt.clientX - previousPosition.x;
  69382. _this._offsetY = -(evt.clientY - previousPosition.y);
  69383. }
  69384. };
  69385. }
  69386. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69387. if (this._onLostFocus) {
  69388. element.addEventListener("blur", this._onLostFocus);
  69389. }
  69390. };
  69391. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69392. if (this._pointerInput && element) {
  69393. if (this._observer) {
  69394. this.camera.getScene().onPointerObservable.remove(this._observer);
  69395. this._observer = null;
  69396. }
  69397. if (this._onLostFocus) {
  69398. element.removeEventListener("blur", this._onLostFocus);
  69399. this._onLostFocus = null;
  69400. }
  69401. this._pointerPressed = [];
  69402. this._offsetX = null;
  69403. this._offsetY = null;
  69404. }
  69405. };
  69406. FreeCameraTouchInput.prototype.checkInputs = function () {
  69407. if (this._offsetX && this._offsetY) {
  69408. var camera = this.camera;
  69409. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  69410. if (this._pointerPressed.length > 1) {
  69411. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  69412. }
  69413. else {
  69414. var speed = camera._computeLocalCameraSpeed();
  69415. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  69416. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  69417. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  69418. }
  69419. }
  69420. };
  69421. FreeCameraTouchInput.prototype.getClassName = function () {
  69422. return "FreeCameraTouchInput";
  69423. };
  69424. FreeCameraTouchInput.prototype.getSimpleName = function () {
  69425. return "touch";
  69426. };
  69427. __decorate([
  69428. BABYLON.serialize()
  69429. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  69430. __decorate([
  69431. BABYLON.serialize()
  69432. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  69433. return FreeCameraTouchInput;
  69434. }());
  69435. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  69436. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  69437. })(BABYLON || (BABYLON = {}));
  69438. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  69439. var BABYLON;
  69440. (function (BABYLON) {
  69441. // We're mainly based on the logic defined into the FreeCamera code
  69442. var TouchCamera = /** @class */ (function (_super) {
  69443. __extends(TouchCamera, _super);
  69444. //-- end properties for backward compatibility for inputs
  69445. function TouchCamera(name, position, scene) {
  69446. var _this = _super.call(this, name, position, scene) || this;
  69447. _this.inputs.addTouch();
  69448. _this._setupInputs();
  69449. return _this;
  69450. }
  69451. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  69452. //-- Begin properties for backward compatibility for inputs
  69453. get: function () {
  69454. var touch = this.inputs.attached["touch"];
  69455. if (touch)
  69456. return touch.touchAngularSensibility;
  69457. return 0;
  69458. },
  69459. set: function (value) {
  69460. var touch = this.inputs.attached["touch"];
  69461. if (touch)
  69462. touch.touchAngularSensibility = value;
  69463. },
  69464. enumerable: true,
  69465. configurable: true
  69466. });
  69467. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  69468. get: function () {
  69469. var touch = this.inputs.attached["touch"];
  69470. if (touch)
  69471. return touch.touchMoveSensibility;
  69472. return 0;
  69473. },
  69474. set: function (value) {
  69475. var touch = this.inputs.attached["touch"];
  69476. if (touch)
  69477. touch.touchMoveSensibility = value;
  69478. },
  69479. enumerable: true,
  69480. configurable: true
  69481. });
  69482. TouchCamera.prototype.getClassName = function () {
  69483. return "TouchCamera";
  69484. };
  69485. TouchCamera.prototype._setupInputs = function () {
  69486. var mouse = this.inputs.attached["mouse"];
  69487. if (mouse) {
  69488. mouse.touchEnabled = false;
  69489. }
  69490. };
  69491. return TouchCamera;
  69492. }(BABYLON.FreeCamera));
  69493. BABYLON.TouchCamera = TouchCamera;
  69494. })(BABYLON || (BABYLON = {}));
  69495. //# sourceMappingURL=babylon.touchCamera.js.map
  69496. var BABYLON;
  69497. (function (BABYLON) {
  69498. var ProceduralTexture = /** @class */ (function (_super) {
  69499. __extends(ProceduralTexture, _super);
  69500. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  69501. if (fallbackTexture === void 0) { fallbackTexture = null; }
  69502. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69503. if (isCube === void 0) { isCube = false; }
  69504. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69505. _this.isCube = isCube;
  69506. _this.isEnabled = true;
  69507. _this._currentRefreshId = -1;
  69508. _this._refreshRate = 1;
  69509. _this._vertexBuffers = {};
  69510. _this._uniforms = new Array();
  69511. _this._samplers = new Array();
  69512. _this._textures = {};
  69513. _this._floats = {};
  69514. _this._floatsArrays = {};
  69515. _this._colors3 = {};
  69516. _this._colors4 = {};
  69517. _this._vectors2 = {};
  69518. _this._vectors3 = {};
  69519. _this._matrices = {};
  69520. _this._fallbackTextureUsed = false;
  69521. scene.proceduralTextures.push(_this);
  69522. _this._engine = scene.getEngine();
  69523. _this.name = name;
  69524. _this.isRenderTarget = true;
  69525. _this._size = size;
  69526. _this._generateMipMaps = generateMipMaps;
  69527. _this.setFragment(fragment);
  69528. _this._fallbackTexture = fallbackTexture;
  69529. if (isCube) {
  69530. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  69531. _this.setFloat("face", 0);
  69532. }
  69533. else {
  69534. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  69535. }
  69536. // VBO
  69537. var vertices = [];
  69538. vertices.push(1, 1);
  69539. vertices.push(-1, 1);
  69540. vertices.push(-1, -1);
  69541. vertices.push(1, -1);
  69542. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69543. _this._createIndexBuffer();
  69544. return _this;
  69545. }
  69546. ProceduralTexture.prototype._createIndexBuffer = function () {
  69547. var engine = this._engine;
  69548. // Indices
  69549. var indices = [];
  69550. indices.push(0);
  69551. indices.push(1);
  69552. indices.push(2);
  69553. indices.push(0);
  69554. indices.push(2);
  69555. indices.push(3);
  69556. this._indexBuffer = engine.createIndexBuffer(indices);
  69557. };
  69558. ProceduralTexture.prototype._rebuild = function () {
  69559. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69560. if (vb) {
  69561. vb._rebuild();
  69562. }
  69563. this._createIndexBuffer();
  69564. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  69565. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69566. }
  69567. };
  69568. ProceduralTexture.prototype.reset = function () {
  69569. if (this._effect === undefined) {
  69570. return;
  69571. }
  69572. var engine = this._engine;
  69573. engine._releaseEffect(this._effect);
  69574. };
  69575. ProceduralTexture.prototype.isReady = function () {
  69576. var _this = this;
  69577. var engine = this._engine;
  69578. var shaders;
  69579. if (!this._fragment) {
  69580. return false;
  69581. }
  69582. if (this._fallbackTextureUsed) {
  69583. return true;
  69584. }
  69585. if (this._fragment.fragmentElement !== undefined) {
  69586. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  69587. }
  69588. else {
  69589. shaders = { vertex: "procedural", fragment: this._fragment };
  69590. }
  69591. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  69592. _this.releaseInternalTexture();
  69593. if (_this._fallbackTexture) {
  69594. _this._texture = _this._fallbackTexture._texture;
  69595. if (_this._texture) {
  69596. _this._texture.incrementReferences();
  69597. }
  69598. }
  69599. _this._fallbackTextureUsed = true;
  69600. });
  69601. return this._effect.isReady();
  69602. };
  69603. ProceduralTexture.prototype.resetRefreshCounter = function () {
  69604. this._currentRefreshId = -1;
  69605. };
  69606. ProceduralTexture.prototype.setFragment = function (fragment) {
  69607. this._fragment = fragment;
  69608. };
  69609. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  69610. get: function () {
  69611. return this._refreshRate;
  69612. },
  69613. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69614. set: function (value) {
  69615. this._refreshRate = value;
  69616. this.resetRefreshCounter();
  69617. },
  69618. enumerable: true,
  69619. configurable: true
  69620. });
  69621. ProceduralTexture.prototype._shouldRender = function () {
  69622. if (!this.isEnabled || !this.isReady() || !this._texture) {
  69623. return false;
  69624. }
  69625. if (this._fallbackTextureUsed) {
  69626. return false;
  69627. }
  69628. if (this._currentRefreshId === -1) { // At least render once
  69629. this._currentRefreshId = 1;
  69630. return true;
  69631. }
  69632. if (this.refreshRate === this._currentRefreshId) {
  69633. this._currentRefreshId = 1;
  69634. return true;
  69635. }
  69636. this._currentRefreshId++;
  69637. return false;
  69638. };
  69639. ProceduralTexture.prototype.getRenderSize = function () {
  69640. return this._size;
  69641. };
  69642. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  69643. if (this._fallbackTextureUsed) {
  69644. return;
  69645. }
  69646. this.releaseInternalTexture();
  69647. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  69648. // Update properties
  69649. this._size = size;
  69650. this._generateMipMaps = generateMipMaps;
  69651. };
  69652. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  69653. if (this._uniforms.indexOf(uniformName) === -1) {
  69654. this._uniforms.push(uniformName);
  69655. }
  69656. };
  69657. ProceduralTexture.prototype.setTexture = function (name, texture) {
  69658. if (this._samplers.indexOf(name) === -1) {
  69659. this._samplers.push(name);
  69660. }
  69661. this._textures[name] = texture;
  69662. return this;
  69663. };
  69664. ProceduralTexture.prototype.setFloat = function (name, value) {
  69665. this._checkUniform(name);
  69666. this._floats[name] = value;
  69667. return this;
  69668. };
  69669. ProceduralTexture.prototype.setFloats = function (name, value) {
  69670. this._checkUniform(name);
  69671. this._floatsArrays[name] = value;
  69672. return this;
  69673. };
  69674. ProceduralTexture.prototype.setColor3 = function (name, value) {
  69675. this._checkUniform(name);
  69676. this._colors3[name] = value;
  69677. return this;
  69678. };
  69679. ProceduralTexture.prototype.setColor4 = function (name, value) {
  69680. this._checkUniform(name);
  69681. this._colors4[name] = value;
  69682. return this;
  69683. };
  69684. ProceduralTexture.prototype.setVector2 = function (name, value) {
  69685. this._checkUniform(name);
  69686. this._vectors2[name] = value;
  69687. return this;
  69688. };
  69689. ProceduralTexture.prototype.setVector3 = function (name, value) {
  69690. this._checkUniform(name);
  69691. this._vectors3[name] = value;
  69692. return this;
  69693. };
  69694. ProceduralTexture.prototype.setMatrix = function (name, value) {
  69695. this._checkUniform(name);
  69696. this._matrices[name] = value;
  69697. return this;
  69698. };
  69699. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69700. var scene = this.getScene();
  69701. if (!scene) {
  69702. return;
  69703. }
  69704. var engine = this._engine;
  69705. // Render
  69706. engine.enableEffect(this._effect);
  69707. engine.setState(false);
  69708. // Texture
  69709. for (var name in this._textures) {
  69710. this._effect.setTexture(name, this._textures[name]);
  69711. }
  69712. // Float
  69713. for (name in this._floats) {
  69714. this._effect.setFloat(name, this._floats[name]);
  69715. }
  69716. // Floats
  69717. for (name in this._floatsArrays) {
  69718. this._effect.setArray(name, this._floatsArrays[name]);
  69719. }
  69720. // Color3
  69721. for (name in this._colors3) {
  69722. this._effect.setColor3(name, this._colors3[name]);
  69723. }
  69724. // Color4
  69725. for (name in this._colors4) {
  69726. var color = this._colors4[name];
  69727. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  69728. }
  69729. // Vector2
  69730. for (name in this._vectors2) {
  69731. this._effect.setVector2(name, this._vectors2[name]);
  69732. }
  69733. // Vector3
  69734. for (name in this._vectors3) {
  69735. this._effect.setVector3(name, this._vectors3[name]);
  69736. }
  69737. // Matrix
  69738. for (name in this._matrices) {
  69739. this._effect.setMatrix(name, this._matrices[name]);
  69740. }
  69741. if (!this._texture) {
  69742. return;
  69743. }
  69744. if (this.isCube) {
  69745. for (var face = 0; face < 6; face++) {
  69746. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  69747. // VBOs
  69748. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69749. this._effect.setFloat("face", face);
  69750. // Clear
  69751. engine.clear(scene.clearColor, true, true, true);
  69752. // Draw order
  69753. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69754. // Mipmaps
  69755. if (face === 5) {
  69756. engine.generateMipMapsForCubemap(this._texture);
  69757. }
  69758. }
  69759. }
  69760. else {
  69761. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  69762. // VBOs
  69763. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69764. // Clear
  69765. engine.clear(scene.clearColor, true, true, true);
  69766. // Draw order
  69767. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69768. }
  69769. // Unbind
  69770. engine.unBindFramebuffer(this._texture, this.isCube);
  69771. if (this.onGenerated) {
  69772. this.onGenerated();
  69773. }
  69774. };
  69775. ProceduralTexture.prototype.clone = function () {
  69776. var textureSize = this.getSize();
  69777. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  69778. // Base texture
  69779. newTexture.hasAlpha = this.hasAlpha;
  69780. newTexture.level = this.level;
  69781. // RenderTarget Texture
  69782. newTexture.coordinatesMode = this.coordinatesMode;
  69783. return newTexture;
  69784. };
  69785. ProceduralTexture.prototype.dispose = function () {
  69786. var scene = this.getScene();
  69787. if (!scene) {
  69788. return;
  69789. }
  69790. var index = scene.proceduralTextures.indexOf(this);
  69791. if (index >= 0) {
  69792. scene.proceduralTextures.splice(index, 1);
  69793. }
  69794. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69795. if (vertexBuffer) {
  69796. vertexBuffer.dispose();
  69797. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69798. }
  69799. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  69800. this._indexBuffer = null;
  69801. }
  69802. _super.prototype.dispose.call(this);
  69803. };
  69804. __decorate([
  69805. BABYLON.serialize()
  69806. ], ProceduralTexture.prototype, "_size", void 0);
  69807. __decorate([
  69808. BABYLON.serialize()
  69809. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  69810. __decorate([
  69811. BABYLON.serialize()
  69812. ], ProceduralTexture.prototype, "isEnabled", void 0);
  69813. __decorate([
  69814. BABYLON.serialize()
  69815. ], ProceduralTexture.prototype, "refreshRate", null);
  69816. return ProceduralTexture;
  69817. }(BABYLON.Texture));
  69818. BABYLON.ProceduralTexture = ProceduralTexture;
  69819. })(BABYLON || (BABYLON = {}));
  69820. //# sourceMappingURL=babylon.proceduralTexture.js.map
  69821. var BABYLON;
  69822. (function (BABYLON) {
  69823. var CustomProceduralTexture = /** @class */ (function (_super) {
  69824. __extends(CustomProceduralTexture, _super);
  69825. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  69826. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  69827. _this._animate = true;
  69828. _this._time = 0;
  69829. _this._texturePath = texturePath;
  69830. //Try to load json
  69831. _this.loadJson(texturePath);
  69832. _this.refreshRate = 1;
  69833. return _this;
  69834. }
  69835. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  69836. var _this = this;
  69837. var noConfigFile = function () {
  69838. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  69839. try {
  69840. _this.setFragment(_this._texturePath);
  69841. }
  69842. catch (ex) {
  69843. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  69844. }
  69845. };
  69846. var configFileUrl = jsonUrl + "/config.json";
  69847. var xhr = new XMLHttpRequest();
  69848. xhr.open("GET", configFileUrl, true);
  69849. xhr.addEventListener("load", function () {
  69850. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69851. try {
  69852. _this._config = JSON.parse(xhr.response);
  69853. _this.updateShaderUniforms();
  69854. _this.updateTextures();
  69855. _this.setFragment(_this._texturePath + "/custom");
  69856. _this._animate = _this._config.animate;
  69857. _this.refreshRate = _this._config.refreshrate;
  69858. }
  69859. catch (ex) {
  69860. noConfigFile();
  69861. }
  69862. }
  69863. else {
  69864. noConfigFile();
  69865. }
  69866. }, false);
  69867. xhr.addEventListener("error", function () {
  69868. noConfigFile();
  69869. }, false);
  69870. try {
  69871. xhr.send();
  69872. }
  69873. catch (ex) {
  69874. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  69875. }
  69876. };
  69877. CustomProceduralTexture.prototype.isReady = function () {
  69878. if (!_super.prototype.isReady.call(this)) {
  69879. return false;
  69880. }
  69881. for (var name in this._textures) {
  69882. var texture = this._textures[name];
  69883. if (!texture.isReady()) {
  69884. return false;
  69885. }
  69886. }
  69887. return true;
  69888. };
  69889. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69890. var scene = this.getScene();
  69891. if (this._animate && scene) {
  69892. this._time += scene.getAnimationRatio() * 0.03;
  69893. this.updateShaderUniforms();
  69894. }
  69895. _super.prototype.render.call(this, useCameraPostProcess);
  69896. };
  69897. CustomProceduralTexture.prototype.updateTextures = function () {
  69898. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  69899. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  69900. }
  69901. };
  69902. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  69903. if (this._config) {
  69904. for (var j = 0; j < this._config.uniforms.length; j++) {
  69905. var uniform = this._config.uniforms[j];
  69906. switch (uniform.type) {
  69907. case "float":
  69908. this.setFloat(uniform.name, uniform.value);
  69909. break;
  69910. case "color3":
  69911. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  69912. break;
  69913. case "color4":
  69914. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  69915. break;
  69916. case "vector2":
  69917. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  69918. break;
  69919. case "vector3":
  69920. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  69921. break;
  69922. }
  69923. }
  69924. }
  69925. this.setFloat("time", this._time);
  69926. };
  69927. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  69928. get: function () {
  69929. return this._animate;
  69930. },
  69931. set: function (value) {
  69932. this._animate = value;
  69933. },
  69934. enumerable: true,
  69935. configurable: true
  69936. });
  69937. return CustomProceduralTexture;
  69938. }(BABYLON.ProceduralTexture));
  69939. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  69940. })(BABYLON || (BABYLON = {}));
  69941. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  69942. var BABYLON;
  69943. (function (BABYLON) {
  69944. var FreeCameraGamepadInput = /** @class */ (function () {
  69945. function FreeCameraGamepadInput() {
  69946. this.gamepadAngularSensibility = 200;
  69947. this.gamepadMoveSensibility = 40;
  69948. // private members
  69949. this._cameraTransform = BABYLON.Matrix.Identity();
  69950. this._deltaTransform = BABYLON.Vector3.Zero();
  69951. this._vector3 = BABYLON.Vector3.Zero();
  69952. this._vector2 = BABYLON.Vector2.Zero();
  69953. }
  69954. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69955. var _this = this;
  69956. var manager = this.camera.getScene().gamepadManager;
  69957. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69958. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69959. // prioritize XBOX gamepads.
  69960. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69961. _this.gamepad = gamepad;
  69962. }
  69963. }
  69964. });
  69965. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69966. if (_this.gamepad === gamepad) {
  69967. _this.gamepad = null;
  69968. }
  69969. });
  69970. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  69971. };
  69972. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  69973. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69974. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69975. this.gamepad = null;
  69976. };
  69977. FreeCameraGamepadInput.prototype.checkInputs = function () {
  69978. if (this.gamepad && this.gamepad.leftStick) {
  69979. var camera = this.camera;
  69980. var LSValues = this.gamepad.leftStick;
  69981. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  69982. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  69983. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  69984. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  69985. var RSValues = this.gamepad.rightStick;
  69986. if (RSValues) {
  69987. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  69988. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  69989. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  69990. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  69991. }
  69992. else {
  69993. RSValues = { x: 0, y: 0 };
  69994. }
  69995. if (!camera.rotationQuaternion) {
  69996. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  69997. }
  69998. else {
  69999. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70000. }
  70001. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70002. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70003. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70004. camera.cameraDirection.addInPlace(this._deltaTransform);
  70005. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70006. camera.cameraRotation.addInPlace(this._vector2);
  70007. }
  70008. };
  70009. FreeCameraGamepadInput.prototype.getClassName = function () {
  70010. return "FreeCameraGamepadInput";
  70011. };
  70012. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70013. return "gamepad";
  70014. };
  70015. __decorate([
  70016. BABYLON.serialize()
  70017. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70018. __decorate([
  70019. BABYLON.serialize()
  70020. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70021. return FreeCameraGamepadInput;
  70022. }());
  70023. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70024. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70025. })(BABYLON || (BABYLON = {}));
  70026. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70027. var BABYLON;
  70028. (function (BABYLON) {
  70029. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70030. function ArcRotateCameraGamepadInput() {
  70031. this.gamepadRotationSensibility = 80;
  70032. this.gamepadMoveSensibility = 40;
  70033. }
  70034. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70035. var _this = this;
  70036. var manager = this.camera.getScene().gamepadManager;
  70037. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70038. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70039. // prioritize XBOX gamepads.
  70040. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70041. _this.gamepad = gamepad;
  70042. }
  70043. }
  70044. });
  70045. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70046. if (_this.gamepad === gamepad) {
  70047. _this.gamepad = null;
  70048. }
  70049. });
  70050. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70051. };
  70052. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70053. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70054. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70055. this.gamepad = null;
  70056. };
  70057. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70058. if (this.gamepad) {
  70059. var camera = this.camera;
  70060. var RSValues = this.gamepad.rightStick;
  70061. if (RSValues) {
  70062. if (RSValues.x != 0) {
  70063. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70064. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70065. camera.inertialAlphaOffset += normalizedRX;
  70066. }
  70067. }
  70068. if (RSValues.y != 0) {
  70069. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70070. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70071. camera.inertialBetaOffset += normalizedRY;
  70072. }
  70073. }
  70074. }
  70075. var LSValues = this.gamepad.leftStick;
  70076. if (LSValues && LSValues.y != 0) {
  70077. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70078. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70079. this.camera.inertialRadiusOffset -= normalizedLY;
  70080. }
  70081. }
  70082. }
  70083. };
  70084. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70085. return "ArcRotateCameraGamepadInput";
  70086. };
  70087. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70088. return "gamepad";
  70089. };
  70090. __decorate([
  70091. BABYLON.serialize()
  70092. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70093. __decorate([
  70094. BABYLON.serialize()
  70095. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70096. return ArcRotateCameraGamepadInput;
  70097. }());
  70098. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70099. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70100. })(BABYLON || (BABYLON = {}));
  70101. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70102. var BABYLON;
  70103. (function (BABYLON) {
  70104. var GamepadManager = /** @class */ (function () {
  70105. function GamepadManager(_scene) {
  70106. var _this = this;
  70107. this._scene = _scene;
  70108. this._babylonGamepads = [];
  70109. this._oneGamepadConnected = false;
  70110. this._isMonitoring = false;
  70111. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70112. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70113. this._gamepadEventSupported = false;
  70114. }
  70115. else {
  70116. this._gamepadEventSupported = 'GamepadEvent' in window;
  70117. this._gamepadSupport = (navigator.getGamepads ||
  70118. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70119. }
  70120. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70121. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70122. for (var i in _this._babylonGamepads) {
  70123. var gamepad = _this._babylonGamepads[i];
  70124. if (gamepad && gamepad._isConnected) {
  70125. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70126. }
  70127. }
  70128. });
  70129. this._onGamepadConnectedEvent = function (evt) {
  70130. var gamepad = evt.gamepad;
  70131. if (gamepad.index in _this._babylonGamepads) {
  70132. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70133. return;
  70134. }
  70135. }
  70136. var newGamepad;
  70137. if (_this._babylonGamepads[gamepad.index]) {
  70138. newGamepad = _this._babylonGamepads[gamepad.index];
  70139. newGamepad.browserGamepad = gamepad;
  70140. newGamepad._isConnected = true;
  70141. }
  70142. else {
  70143. newGamepad = _this._addNewGamepad(gamepad);
  70144. }
  70145. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70146. _this._startMonitoringGamepads();
  70147. };
  70148. this._onGamepadDisconnectedEvent = function (evt) {
  70149. var gamepad = evt.gamepad;
  70150. // Remove the gamepad from the list of gamepads to monitor.
  70151. for (var i in _this._babylonGamepads) {
  70152. if (_this._babylonGamepads[i].index === gamepad.index) {
  70153. var disconnectedGamepad = _this._babylonGamepads[i];
  70154. disconnectedGamepad._isConnected = false;
  70155. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70156. break;
  70157. }
  70158. }
  70159. };
  70160. if (this._gamepadSupport) {
  70161. //first add already-connected gamepads
  70162. this._updateGamepadObjects();
  70163. if (this._babylonGamepads.length) {
  70164. this._startMonitoringGamepads();
  70165. }
  70166. // Checking if the gamepad connected event is supported (like in Firefox)
  70167. if (this._gamepadEventSupported) {
  70168. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70169. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70170. }
  70171. else {
  70172. this._startMonitoringGamepads();
  70173. }
  70174. }
  70175. }
  70176. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70177. get: function () {
  70178. return this._babylonGamepads;
  70179. },
  70180. enumerable: true,
  70181. configurable: true
  70182. });
  70183. GamepadManager.prototype.getGamepadByType = function (type) {
  70184. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70185. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70186. var gamepad = _a[_i];
  70187. if (gamepad && gamepad.type === type) {
  70188. return gamepad;
  70189. }
  70190. }
  70191. return null;
  70192. };
  70193. GamepadManager.prototype.dispose = function () {
  70194. if (this._gamepadEventSupported) {
  70195. if (this._onGamepadConnectedEvent) {
  70196. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70197. }
  70198. if (this._onGamepadDisconnectedEvent) {
  70199. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70200. }
  70201. this._onGamepadConnectedEvent = null;
  70202. this._onGamepadDisconnectedEvent = null;
  70203. }
  70204. this._babylonGamepads.forEach(function (gamepad) {
  70205. gamepad.dispose();
  70206. });
  70207. this.onGamepadConnectedObservable.clear();
  70208. this.onGamepadDisconnectedObservable.clear();
  70209. this._oneGamepadConnected = false;
  70210. this._stopMonitoringGamepads();
  70211. this._babylonGamepads = [];
  70212. };
  70213. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70214. if (!this._oneGamepadConnected) {
  70215. this._oneGamepadConnected = true;
  70216. }
  70217. var newGamepad;
  70218. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70219. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70220. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70221. }
  70222. // if pose is supported, use the (WebVR) pose enabled controller
  70223. else if (gamepad.pose) {
  70224. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70225. }
  70226. else {
  70227. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70228. }
  70229. this._babylonGamepads[newGamepad.index] = newGamepad;
  70230. return newGamepad;
  70231. };
  70232. GamepadManager.prototype._startMonitoringGamepads = function () {
  70233. if (!this._isMonitoring) {
  70234. this._isMonitoring = true;
  70235. //back-comp
  70236. if (!this._scene) {
  70237. this._checkGamepadsStatus();
  70238. }
  70239. }
  70240. };
  70241. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70242. this._isMonitoring = false;
  70243. };
  70244. GamepadManager.prototype._checkGamepadsStatus = function () {
  70245. var _this = this;
  70246. // Hack to be compatible Chrome
  70247. this._updateGamepadObjects();
  70248. for (var i in this._babylonGamepads) {
  70249. var gamepad = this._babylonGamepads[i];
  70250. if (!gamepad || !gamepad.isConnected) {
  70251. continue;
  70252. }
  70253. gamepad.update();
  70254. }
  70255. if (this._isMonitoring && !this._scene) {
  70256. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70257. }
  70258. };
  70259. // This function is called only on Chrome, which does not properly support
  70260. // connection/disconnection events and forces you to recopy again the gamepad object
  70261. GamepadManager.prototype._updateGamepadObjects = function () {
  70262. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70263. for (var i = 0; i < gamepads.length; i++) {
  70264. var gamepad = gamepads[i];
  70265. if (gamepad) {
  70266. if (!this._babylonGamepads[gamepad.index]) {
  70267. var newGamepad = this._addNewGamepad(gamepad);
  70268. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70269. }
  70270. else {
  70271. // Forced to copy again this object for Chrome for unknown reason
  70272. this._babylonGamepads[i].browserGamepad = gamepad;
  70273. if (!this._babylonGamepads[i].isConnected) {
  70274. this._babylonGamepads[i]._isConnected = true;
  70275. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70276. }
  70277. }
  70278. }
  70279. }
  70280. };
  70281. return GamepadManager;
  70282. }());
  70283. BABYLON.GamepadManager = GamepadManager;
  70284. })(BABYLON || (BABYLON = {}));
  70285. //# sourceMappingURL=babylon.gamepadManager.js.map
  70286. var BABYLON;
  70287. (function (BABYLON) {
  70288. var StickValues = /** @class */ (function () {
  70289. function StickValues(x, y) {
  70290. this.x = x;
  70291. this.y = y;
  70292. }
  70293. return StickValues;
  70294. }());
  70295. BABYLON.StickValues = StickValues;
  70296. var Gamepad = /** @class */ (function () {
  70297. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70298. if (leftStickX === void 0) { leftStickX = 0; }
  70299. if (leftStickY === void 0) { leftStickY = 1; }
  70300. if (rightStickX === void 0) { rightStickX = 2; }
  70301. if (rightStickY === void 0) { rightStickY = 3; }
  70302. this.id = id;
  70303. this.index = index;
  70304. this.browserGamepad = browserGamepad;
  70305. this._isConnected = true;
  70306. this._invertLeftStickY = false;
  70307. this.type = Gamepad.GAMEPAD;
  70308. this._leftStickAxisX = leftStickX;
  70309. this._leftStickAxisY = leftStickY;
  70310. this._rightStickAxisX = rightStickX;
  70311. this._rightStickAxisY = rightStickY;
  70312. if (this.browserGamepad.axes.length >= 2) {
  70313. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70314. }
  70315. if (this.browserGamepad.axes.length >= 4) {
  70316. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70317. }
  70318. }
  70319. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70320. get: function () {
  70321. return this._isConnected;
  70322. },
  70323. enumerable: true,
  70324. configurable: true
  70325. });
  70326. Gamepad.prototype.onleftstickchanged = function (callback) {
  70327. this._onleftstickchanged = callback;
  70328. };
  70329. Gamepad.prototype.onrightstickchanged = function (callback) {
  70330. this._onrightstickchanged = callback;
  70331. };
  70332. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70333. get: function () {
  70334. return this._leftStick;
  70335. },
  70336. set: function (newValues) {
  70337. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70338. this._onleftstickchanged(newValues);
  70339. }
  70340. this._leftStick = newValues;
  70341. },
  70342. enumerable: true,
  70343. configurable: true
  70344. });
  70345. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70346. get: function () {
  70347. return this._rightStick;
  70348. },
  70349. set: function (newValues) {
  70350. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70351. this._onrightstickchanged(newValues);
  70352. }
  70353. this._rightStick = newValues;
  70354. },
  70355. enumerable: true,
  70356. configurable: true
  70357. });
  70358. Gamepad.prototype.update = function () {
  70359. if (this._leftStick) {
  70360. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70361. if (this._invertLeftStickY) {
  70362. this.leftStick.y *= -1;
  70363. }
  70364. }
  70365. if (this._rightStick) {
  70366. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70367. }
  70368. };
  70369. Gamepad.prototype.dispose = function () {
  70370. };
  70371. Gamepad.GAMEPAD = 0;
  70372. Gamepad.GENERIC = 1;
  70373. Gamepad.XBOX = 2;
  70374. Gamepad.POSE_ENABLED = 3;
  70375. return Gamepad;
  70376. }());
  70377. BABYLON.Gamepad = Gamepad;
  70378. var GenericPad = /** @class */ (function (_super) {
  70379. __extends(GenericPad, _super);
  70380. function GenericPad(id, index, browserGamepad) {
  70381. var _this = _super.call(this, id, index, browserGamepad) || this;
  70382. _this.onButtonDownObservable = new BABYLON.Observable();
  70383. _this.onButtonUpObservable = new BABYLON.Observable();
  70384. _this.type = Gamepad.GENERIC;
  70385. _this._buttons = new Array(browserGamepad.buttons.length);
  70386. return _this;
  70387. }
  70388. GenericPad.prototype.onbuttondown = function (callback) {
  70389. this._onbuttondown = callback;
  70390. };
  70391. GenericPad.prototype.onbuttonup = function (callback) {
  70392. this._onbuttonup = callback;
  70393. };
  70394. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70395. if (newValue !== currentValue) {
  70396. if (newValue === 1) {
  70397. if (this._onbuttondown) {
  70398. this._onbuttondown(buttonIndex);
  70399. }
  70400. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70401. }
  70402. if (newValue === 0) {
  70403. if (this._onbuttonup) {
  70404. this._onbuttonup(buttonIndex);
  70405. }
  70406. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70407. }
  70408. }
  70409. return newValue;
  70410. };
  70411. GenericPad.prototype.update = function () {
  70412. _super.prototype.update.call(this);
  70413. for (var index = 0; index < this._buttons.length; index++) {
  70414. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  70415. }
  70416. };
  70417. GenericPad.prototype.dispose = function () {
  70418. _super.prototype.dispose.call(this);
  70419. this.onButtonDownObservable.clear();
  70420. this.onButtonUpObservable.clear();
  70421. };
  70422. return GenericPad;
  70423. }(Gamepad));
  70424. BABYLON.GenericPad = GenericPad;
  70425. })(BABYLON || (BABYLON = {}));
  70426. //# sourceMappingURL=babylon.gamepad.js.map
  70427. var BABYLON;
  70428. (function (BABYLON) {
  70429. /**
  70430. * Defines supported buttons for XBox360 compatible gamepads
  70431. */
  70432. var Xbox360Button;
  70433. (function (Xbox360Button) {
  70434. /** A */
  70435. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  70436. /** B */
  70437. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  70438. /** X */
  70439. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  70440. /** Y */
  70441. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  70442. /** Start */
  70443. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  70444. /** Back */
  70445. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  70446. /** Left button */
  70447. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  70448. /** Right button */
  70449. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  70450. /** Left stick */
  70451. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  70452. /** Right stick */
  70453. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  70454. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  70455. /** Defines values for XBox360 DPad */
  70456. var Xbox360Dpad;
  70457. (function (Xbox360Dpad) {
  70458. /** Up */
  70459. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  70460. /** Down */
  70461. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  70462. /** Left */
  70463. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  70464. /** Right */
  70465. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  70466. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  70467. /**
  70468. * Defines a XBox360 gamepad
  70469. */
  70470. var Xbox360Pad = /** @class */ (function (_super) {
  70471. __extends(Xbox360Pad, _super);
  70472. /**
  70473. * Creates a new XBox360 gamepad object
  70474. * @param id defines the id of this gamepad
  70475. * @param index defines its index
  70476. * @param gamepad defines the internal HTML gamepad object
  70477. * @param xboxOne defines if it is a XBox One gamepad
  70478. */
  70479. function Xbox360Pad(id, index, gamepad, xboxOne) {
  70480. if (xboxOne === void 0) { xboxOne = false; }
  70481. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  70482. _this._leftTrigger = 0;
  70483. _this._rightTrigger = 0;
  70484. /** Observable raised when a button is pressed */
  70485. _this.onButtonDownObservable = new BABYLON.Observable();
  70486. /** Observable raised when a button is released */
  70487. _this.onButtonUpObservable = new BABYLON.Observable();
  70488. /** Observable raised when a pad is pressed */
  70489. _this.onPadDownObservable = new BABYLON.Observable();
  70490. /** Observable raised when a pad is released */
  70491. _this.onPadUpObservable = new BABYLON.Observable();
  70492. _this._buttonA = 0;
  70493. _this._buttonB = 0;
  70494. _this._buttonX = 0;
  70495. _this._buttonY = 0;
  70496. _this._buttonBack = 0;
  70497. _this._buttonStart = 0;
  70498. _this._buttonLB = 0;
  70499. _this._buttonRB = 0;
  70500. _this._buttonLeftStick = 0;
  70501. _this._buttonRightStick = 0;
  70502. _this._dPadUp = 0;
  70503. _this._dPadDown = 0;
  70504. _this._dPadLeft = 0;
  70505. _this._dPadRight = 0;
  70506. _this._isXboxOnePad = false;
  70507. _this.type = BABYLON.Gamepad.XBOX;
  70508. _this._isXboxOnePad = xboxOne;
  70509. return _this;
  70510. }
  70511. /**
  70512. * Defines the callback to call when left trigger is pressed
  70513. * @param callback defines the callback to use
  70514. */
  70515. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  70516. this._onlefttriggerchanged = callback;
  70517. };
  70518. /**
  70519. * Defines the callback to call when right trigger is pressed
  70520. * @param callback defines the callback to use
  70521. */
  70522. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  70523. this._onrighttriggerchanged = callback;
  70524. };
  70525. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  70526. /**
  70527. * Gets or sets left trigger value
  70528. */
  70529. get: function () {
  70530. return this._leftTrigger;
  70531. },
  70532. set: function (newValue) {
  70533. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  70534. this._onlefttriggerchanged(newValue);
  70535. }
  70536. this._leftTrigger = newValue;
  70537. },
  70538. enumerable: true,
  70539. configurable: true
  70540. });
  70541. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  70542. /**
  70543. * Gets or sets right trigger value
  70544. */
  70545. get: function () {
  70546. return this._rightTrigger;
  70547. },
  70548. set: function (newValue) {
  70549. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  70550. this._onrighttriggerchanged(newValue);
  70551. }
  70552. this._rightTrigger = newValue;
  70553. },
  70554. enumerable: true,
  70555. configurable: true
  70556. });
  70557. /**
  70558. * Defines the callback to call when a button is pressed
  70559. * @param callback defines the callback to use
  70560. */
  70561. Xbox360Pad.prototype.onbuttondown = function (callback) {
  70562. this._onbuttondown = callback;
  70563. };
  70564. /**
  70565. * Defines the callback to call when a button is released
  70566. * @param callback defines the callback to use
  70567. */
  70568. Xbox360Pad.prototype.onbuttonup = function (callback) {
  70569. this._onbuttonup = callback;
  70570. };
  70571. /**
  70572. * Defines the callback to call when a pad is pressed
  70573. * @param callback defines the callback to use
  70574. */
  70575. Xbox360Pad.prototype.ondpaddown = function (callback) {
  70576. this._ondpaddown = callback;
  70577. };
  70578. /**
  70579. * Defines the callback to call when a pad is released
  70580. * @param callback defines the callback to use
  70581. */
  70582. Xbox360Pad.prototype.ondpadup = function (callback) {
  70583. this._ondpadup = callback;
  70584. };
  70585. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  70586. if (newValue !== currentValue) {
  70587. if (newValue === 1) {
  70588. if (this._onbuttondown) {
  70589. this._onbuttondown(buttonType);
  70590. }
  70591. this.onButtonDownObservable.notifyObservers(buttonType);
  70592. }
  70593. if (newValue === 0) {
  70594. if (this._onbuttonup) {
  70595. this._onbuttonup(buttonType);
  70596. }
  70597. this.onButtonUpObservable.notifyObservers(buttonType);
  70598. }
  70599. }
  70600. return newValue;
  70601. };
  70602. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  70603. if (newValue !== currentValue) {
  70604. if (newValue === 1) {
  70605. if (this._ondpaddown) {
  70606. this._ondpaddown(buttonType);
  70607. }
  70608. this.onPadDownObservable.notifyObservers(buttonType);
  70609. }
  70610. if (newValue === 0) {
  70611. if (this._ondpadup) {
  70612. this._ondpadup(buttonType);
  70613. }
  70614. this.onPadUpObservable.notifyObservers(buttonType);
  70615. }
  70616. }
  70617. return newValue;
  70618. };
  70619. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  70620. /** Gets or sets value of A button */
  70621. get: function () {
  70622. return this._buttonA;
  70623. },
  70624. set: function (value) {
  70625. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  70626. },
  70627. enumerable: true,
  70628. configurable: true
  70629. });
  70630. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  70631. /** Gets or sets value of B button */
  70632. get: function () {
  70633. return this._buttonB;
  70634. },
  70635. set: function (value) {
  70636. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  70637. },
  70638. enumerable: true,
  70639. configurable: true
  70640. });
  70641. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  70642. /** Gets or sets value of X button */
  70643. get: function () {
  70644. return this._buttonX;
  70645. },
  70646. set: function (value) {
  70647. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  70648. },
  70649. enumerable: true,
  70650. configurable: true
  70651. });
  70652. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  70653. /** Gets or sets value of Y button */
  70654. get: function () {
  70655. return this._buttonY;
  70656. },
  70657. set: function (value) {
  70658. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  70659. },
  70660. enumerable: true,
  70661. configurable: true
  70662. });
  70663. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  70664. /** Gets or sets value of Start button */
  70665. get: function () {
  70666. return this._buttonStart;
  70667. },
  70668. set: function (value) {
  70669. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  70670. },
  70671. enumerable: true,
  70672. configurable: true
  70673. });
  70674. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  70675. /** Gets or sets value of Back button */
  70676. get: function () {
  70677. return this._buttonBack;
  70678. },
  70679. set: function (value) {
  70680. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  70681. },
  70682. enumerable: true,
  70683. configurable: true
  70684. });
  70685. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  70686. /** Gets or sets value of Left button */
  70687. get: function () {
  70688. return this._buttonLB;
  70689. },
  70690. set: function (value) {
  70691. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  70692. },
  70693. enumerable: true,
  70694. configurable: true
  70695. });
  70696. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  70697. /** Gets or sets value of Right button */
  70698. get: function () {
  70699. return this._buttonRB;
  70700. },
  70701. set: function (value) {
  70702. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  70703. },
  70704. enumerable: true,
  70705. configurable: true
  70706. });
  70707. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  70708. /** Gets or sets value of left stick */
  70709. get: function () {
  70710. return this._buttonLeftStick;
  70711. },
  70712. set: function (value) {
  70713. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  70714. },
  70715. enumerable: true,
  70716. configurable: true
  70717. });
  70718. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  70719. /** Gets or sets value of right stick */
  70720. get: function () {
  70721. return this._buttonRightStick;
  70722. },
  70723. set: function (value) {
  70724. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  70725. },
  70726. enumerable: true,
  70727. configurable: true
  70728. });
  70729. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  70730. /** Gets or sets value of DPad up */
  70731. get: function () {
  70732. return this._dPadUp;
  70733. },
  70734. set: function (value) {
  70735. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  70736. },
  70737. enumerable: true,
  70738. configurable: true
  70739. });
  70740. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  70741. /** Gets or sets value of DPad down */
  70742. get: function () {
  70743. return this._dPadDown;
  70744. },
  70745. set: function (value) {
  70746. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  70747. },
  70748. enumerable: true,
  70749. configurable: true
  70750. });
  70751. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  70752. /** Gets or sets value of DPad left */
  70753. get: function () {
  70754. return this._dPadLeft;
  70755. },
  70756. set: function (value) {
  70757. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  70758. },
  70759. enumerable: true,
  70760. configurable: true
  70761. });
  70762. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  70763. /** Gets or sets value of DPad right */
  70764. get: function () {
  70765. return this._dPadRight;
  70766. },
  70767. set: function (value) {
  70768. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  70769. },
  70770. enumerable: true,
  70771. configurable: true
  70772. });
  70773. /**
  70774. * Force the gamepad to synchronize with device values
  70775. */
  70776. Xbox360Pad.prototype.update = function () {
  70777. _super.prototype.update.call(this);
  70778. if (this._isXboxOnePad) {
  70779. this.buttonA = this.browserGamepad.buttons[0].value;
  70780. this.buttonB = this.browserGamepad.buttons[1].value;
  70781. this.buttonX = this.browserGamepad.buttons[2].value;
  70782. this.buttonY = this.browserGamepad.buttons[3].value;
  70783. this.buttonLB = this.browserGamepad.buttons[4].value;
  70784. this.buttonRB = this.browserGamepad.buttons[5].value;
  70785. this.leftTrigger = this.browserGamepad.axes[2];
  70786. this.rightTrigger = this.browserGamepad.axes[5];
  70787. this.buttonBack = this.browserGamepad.buttons[9].value;
  70788. this.buttonStart = this.browserGamepad.buttons[8].value;
  70789. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  70790. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  70791. this.dPadUp = this.browserGamepad.buttons[11].value;
  70792. this.dPadDown = this.browserGamepad.buttons[12].value;
  70793. this.dPadLeft = this.browserGamepad.buttons[13].value;
  70794. this.dPadRight = this.browserGamepad.buttons[14].value;
  70795. }
  70796. else {
  70797. this.buttonA = this.browserGamepad.buttons[0].value;
  70798. this.buttonB = this.browserGamepad.buttons[1].value;
  70799. this.buttonX = this.browserGamepad.buttons[2].value;
  70800. this.buttonY = this.browserGamepad.buttons[3].value;
  70801. this.buttonLB = this.browserGamepad.buttons[4].value;
  70802. this.buttonRB = this.browserGamepad.buttons[5].value;
  70803. this.leftTrigger = this.browserGamepad.buttons[6].value;
  70804. this.rightTrigger = this.browserGamepad.buttons[7].value;
  70805. this.buttonBack = this.browserGamepad.buttons[8].value;
  70806. this.buttonStart = this.browserGamepad.buttons[9].value;
  70807. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  70808. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  70809. this.dPadUp = this.browserGamepad.buttons[12].value;
  70810. this.dPadDown = this.browserGamepad.buttons[13].value;
  70811. this.dPadLeft = this.browserGamepad.buttons[14].value;
  70812. this.dPadRight = this.browserGamepad.buttons[15].value;
  70813. }
  70814. };
  70815. Xbox360Pad.prototype.dispose = function () {
  70816. _super.prototype.dispose.call(this);
  70817. this.onButtonDownObservable.clear();
  70818. this.onButtonUpObservable.clear();
  70819. this.onPadDownObservable.clear();
  70820. this.onPadUpObservable.clear();
  70821. };
  70822. return Xbox360Pad;
  70823. }(BABYLON.Gamepad));
  70824. BABYLON.Xbox360Pad = Xbox360Pad;
  70825. })(BABYLON || (BABYLON = {}));
  70826. //# sourceMappingURL=babylon.xboxGamepad.js.map
  70827. var BABYLON;
  70828. (function (BABYLON) {
  70829. /**
  70830. * Defines the types of pose enabled controllers that are supported
  70831. */
  70832. var PoseEnabledControllerType;
  70833. (function (PoseEnabledControllerType) {
  70834. /**
  70835. * HTC Vive
  70836. */
  70837. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  70838. /**
  70839. * Oculus Rift
  70840. */
  70841. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  70842. /**
  70843. * Windows mixed reality
  70844. */
  70845. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  70846. /**
  70847. * Samsung gear VR
  70848. */
  70849. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  70850. /**
  70851. * Google Daydream
  70852. */
  70853. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  70854. /**
  70855. * Generic
  70856. */
  70857. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  70858. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  70859. /**
  70860. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70861. */
  70862. var PoseEnabledControllerHelper = /** @class */ (function () {
  70863. function PoseEnabledControllerHelper() {
  70864. }
  70865. /**
  70866. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70867. * @param vrGamepad the gamepad to initialized
  70868. * @returns a vr controller of the type the gamepad identified as
  70869. */
  70870. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  70871. // Oculus Touch
  70872. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  70873. return new BABYLON.OculusTouchController(vrGamepad);
  70874. }
  70875. // Windows Mixed Reality controllers
  70876. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  70877. return new BABYLON.WindowsMotionController(vrGamepad);
  70878. }
  70879. // HTC Vive
  70880. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  70881. return new BABYLON.ViveController(vrGamepad);
  70882. }
  70883. // Samsung/Oculus Gear VR or Oculus Go
  70884. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  70885. return new BABYLON.GearVRController(vrGamepad);
  70886. }
  70887. // Google Daydream
  70888. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  70889. return new BABYLON.DaydreamController(vrGamepad);
  70890. }
  70891. // Generic
  70892. else {
  70893. return new BABYLON.GenericController(vrGamepad);
  70894. }
  70895. };
  70896. return PoseEnabledControllerHelper;
  70897. }());
  70898. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  70899. /**
  70900. * Defines the PoseEnabledController object that contains state of a vr capable controller
  70901. */
  70902. var PoseEnabledController = /** @class */ (function (_super) {
  70903. __extends(PoseEnabledController, _super);
  70904. /**
  70905. * Creates a new PoseEnabledController from a gamepad
  70906. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  70907. */
  70908. function PoseEnabledController(browserGamepad) {
  70909. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  70910. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  70911. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  70912. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  70913. /**
  70914. * The device position in babylon space
  70915. */
  70916. _this.devicePosition = BABYLON.Vector3.Zero();
  70917. /**
  70918. * The device rotation in babylon space
  70919. */
  70920. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  70921. /**
  70922. * The scale factor of the device in babylon space
  70923. */
  70924. _this.deviceScaleFactor = 1;
  70925. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  70926. /**
  70927. * Internal, matrix used to convert room space to babylon space
  70928. */
  70929. _this._deviceToWorld = BABYLON.Matrix.Identity();
  70930. /**
  70931. * Node to be used when casting a ray from the controller
  70932. */
  70933. _this._pointingPoseNode = null;
  70934. _this._workingMatrix = BABYLON.Matrix.Identity();
  70935. /**
  70936. * @hidden
  70937. */
  70938. _this._meshAttachedObservable = new BABYLON.Observable();
  70939. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  70940. _this.controllerType = PoseEnabledControllerType.GENERIC;
  70941. _this.position = BABYLON.Vector3.Zero();
  70942. _this.rotationQuaternion = new BABYLON.Quaternion();
  70943. _this._calculatedPosition = BABYLON.Vector3.Zero();
  70944. _this._calculatedRotation = new BABYLON.Quaternion();
  70945. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  70946. return _this;
  70947. }
  70948. /**
  70949. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  70950. */
  70951. PoseEnabledController.prototype.update = function () {
  70952. _super.prototype.update.call(this);
  70953. var pose = this.browserGamepad.pose;
  70954. this.updateFromDevice(pose);
  70955. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  70956. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  70957. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  70958. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  70959. if (this._mesh) {
  70960. this._mesh.position.copyFrom(this.devicePosition);
  70961. if (this._mesh.rotationQuaternion) {
  70962. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  70963. }
  70964. }
  70965. };
  70966. /**
  70967. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  70968. * @param poseData raw pose fromthe device
  70969. */
  70970. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  70971. if (poseData) {
  70972. this.rawPose = poseData;
  70973. if (poseData.position) {
  70974. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  70975. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  70976. this._deviceRoomPosition.z *= -1;
  70977. }
  70978. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  70979. this._calculatedPosition.addInPlace(this.position);
  70980. }
  70981. var pose = this.rawPose;
  70982. if (poseData.orientation && pose.orientation) {
  70983. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  70984. if (this._mesh) {
  70985. if (this._mesh.getScene().useRightHandedSystem) {
  70986. this._deviceRoomRotationQuaternion.z *= -1;
  70987. this._deviceRoomRotationQuaternion.w *= -1;
  70988. }
  70989. else {
  70990. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  70991. }
  70992. }
  70993. // if the camera is set, rotate to the camera's rotation
  70994. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  70995. }
  70996. }
  70997. };
  70998. /**
  70999. * Attaches a mesh to the controller
  71000. * @param mesh the mesh to be attached
  71001. */
  71002. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71003. if (this._mesh) {
  71004. this._mesh.parent = null;
  71005. }
  71006. this._mesh = mesh;
  71007. if (this._poseControlledCamera) {
  71008. this._mesh.parent = this._poseControlledCamera;
  71009. }
  71010. if (!this._mesh.rotationQuaternion) {
  71011. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71012. }
  71013. // Sync controller mesh and pointing pose node's state with controller
  71014. this.update();
  71015. if (this._pointingPoseNode) {
  71016. var parents = [];
  71017. var obj = this._pointingPoseNode;
  71018. while (obj.parent) {
  71019. parents.push(obj.parent);
  71020. obj = obj.parent;
  71021. }
  71022. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  71023. }
  71024. this._meshAttachedObservable.notifyObservers(mesh);
  71025. };
  71026. /**
  71027. * Attaches the controllers mesh to a camera
  71028. * @param camera the camera the mesh should be attached to
  71029. */
  71030. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71031. this._poseControlledCamera = camera;
  71032. if (this._mesh) {
  71033. this._mesh.parent = this._poseControlledCamera;
  71034. }
  71035. };
  71036. /**
  71037. * Disposes of the controller
  71038. */
  71039. PoseEnabledController.prototype.dispose = function () {
  71040. if (this._mesh) {
  71041. this._mesh.dispose();
  71042. }
  71043. this._mesh = null;
  71044. _super.prototype.dispose.call(this);
  71045. };
  71046. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71047. /**
  71048. * The mesh that is attached to the controller
  71049. */
  71050. get: function () {
  71051. return this._mesh;
  71052. },
  71053. enumerable: true,
  71054. configurable: true
  71055. });
  71056. /**
  71057. * Gets the ray of the controller in the direction the controller is pointing
  71058. * @param length the length the resulting ray should be
  71059. * @returns a ray in the direction the controller is pointing
  71060. */
  71061. PoseEnabledController.prototype.getForwardRay = function (length) {
  71062. if (length === void 0) { length = 100; }
  71063. if (!this.mesh) {
  71064. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71065. }
  71066. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71067. var origin = m.getTranslation();
  71068. var forward = new BABYLON.Vector3(0, 0, -1);
  71069. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71070. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71071. return new BABYLON.Ray(origin, direction, length);
  71072. };
  71073. /**
  71074. * Name of the child mesh that can be used to cast a ray from the controller
  71075. */
  71076. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71077. return PoseEnabledController;
  71078. }(BABYLON.Gamepad));
  71079. BABYLON.PoseEnabledController = PoseEnabledController;
  71080. })(BABYLON || (BABYLON = {}));
  71081. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71082. var BABYLON;
  71083. (function (BABYLON) {
  71084. /**
  71085. * Defines the WebVRController object that represents controllers tracked in 3D space
  71086. */
  71087. var WebVRController = /** @class */ (function (_super) {
  71088. __extends(WebVRController, _super);
  71089. /**
  71090. * Creates a new WebVRController from a gamepad
  71091. * @param vrGamepad the gamepad that the WebVRController should be created from
  71092. */
  71093. function WebVRController(vrGamepad) {
  71094. var _this = _super.call(this, vrGamepad) || this;
  71095. // Observables
  71096. /**
  71097. * Fired when the trigger state has changed
  71098. */
  71099. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71100. /**
  71101. * Fired when the main button state has changed
  71102. */
  71103. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71104. /**
  71105. * Fired when the secondary button state has changed
  71106. */
  71107. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71108. /**
  71109. * Fired when the pad state has changed
  71110. */
  71111. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71112. /**
  71113. * Fired when controllers stick values have changed
  71114. */
  71115. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71116. /**
  71117. * X and Y axis corrisponding to the controllers joystick
  71118. */
  71119. _this.pad = { x: 0, y: 0 };
  71120. // avoid GC, store state in a tmp object
  71121. _this._changes = {
  71122. pressChanged: false,
  71123. touchChanged: false,
  71124. valueChanged: false,
  71125. changed: false
  71126. };
  71127. _this._buttons = new Array(vrGamepad.buttons.length);
  71128. _this.hand = vrGamepad.hand;
  71129. return _this;
  71130. }
  71131. /**
  71132. * Fired when a controller button's state has changed
  71133. * @param callback the callback containing the button that was modified
  71134. */
  71135. WebVRController.prototype.onButtonStateChange = function (callback) {
  71136. this._onButtonStateChange = callback;
  71137. };
  71138. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71139. /**
  71140. * The default controller model for the controller
  71141. */
  71142. get: function () {
  71143. return this._defaultModel;
  71144. },
  71145. enumerable: true,
  71146. configurable: true
  71147. });
  71148. /**
  71149. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71150. */
  71151. WebVRController.prototype.update = function () {
  71152. _super.prototype.update.call(this);
  71153. for (var index = 0; index < this._buttons.length; index++) {
  71154. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71155. }
  71156. ;
  71157. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71158. this.pad.x = this.leftStick.x;
  71159. this.pad.y = this.leftStick.y;
  71160. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71161. }
  71162. };
  71163. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71164. if (!newState) {
  71165. newState = {
  71166. pressed: false,
  71167. touched: false,
  71168. value: 0
  71169. };
  71170. }
  71171. if (!currentState) {
  71172. this._buttons[buttonIndex] = {
  71173. pressed: newState.pressed,
  71174. touched: newState.touched,
  71175. value: newState.value
  71176. };
  71177. return;
  71178. }
  71179. this._checkChanges(newState, currentState);
  71180. if (this._changes.changed) {
  71181. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71182. this._handleButtonChange(buttonIndex, newState, this._changes);
  71183. }
  71184. this._buttons[buttonIndex].pressed = newState.pressed;
  71185. this._buttons[buttonIndex].touched = newState.touched;
  71186. // oculus triggers are never 0, thou not touched.
  71187. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71188. };
  71189. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71190. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71191. this._changes.touchChanged = newState.touched !== currentState.touched;
  71192. this._changes.valueChanged = newState.value !== currentState.value;
  71193. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71194. return this._changes;
  71195. };
  71196. /**
  71197. * Disposes of th webVRCOntroller
  71198. */
  71199. WebVRController.prototype.dispose = function () {
  71200. _super.prototype.dispose.call(this);
  71201. this.onTriggerStateChangedObservable.clear();
  71202. this.onMainButtonStateChangedObservable.clear();
  71203. this.onSecondaryButtonStateChangedObservable.clear();
  71204. this.onPadStateChangedObservable.clear();
  71205. this.onPadValuesChangedObservable.clear();
  71206. };
  71207. return WebVRController;
  71208. }(BABYLON.PoseEnabledController));
  71209. BABYLON.WebVRController = WebVRController;
  71210. })(BABYLON || (BABYLON = {}));
  71211. //# sourceMappingURL=babylon.webVRController.js.map
  71212. var BABYLON;
  71213. (function (BABYLON) {
  71214. /**
  71215. * Oculus Touch Controller
  71216. */
  71217. var OculusTouchController = /** @class */ (function (_super) {
  71218. __extends(OculusTouchController, _super);
  71219. /**
  71220. * Creates a new OculusTouchController from a gamepad
  71221. * @param vrGamepad the gamepad that the controller should be created from
  71222. */
  71223. function OculusTouchController(vrGamepad) {
  71224. var _this = _super.call(this, vrGamepad) || this;
  71225. /**
  71226. * Fired when the secondary trigger on this controller is modified
  71227. */
  71228. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71229. /**
  71230. * Fired when the thumb rest on this controller is modified
  71231. */
  71232. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71233. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71234. return _this;
  71235. }
  71236. /**
  71237. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71238. * @param scene scene in which to add meshes
  71239. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71240. */
  71241. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71242. var _this = this;
  71243. var meshName;
  71244. // Hand
  71245. if (this.hand === 'left') {
  71246. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71247. }
  71248. else { // Right is the default if no hand is specified
  71249. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71250. }
  71251. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71252. /*
  71253. Parent Mesh name: oculus_touch_left
  71254. - body
  71255. - trigger
  71256. - thumbstick
  71257. - grip
  71258. - button_y
  71259. - button_x
  71260. - button_enter
  71261. */
  71262. _this._defaultModel = newMeshes[1];
  71263. _this.attachToMesh(_this._defaultModel);
  71264. if (meshLoaded) {
  71265. meshLoaded(_this._defaultModel);
  71266. }
  71267. });
  71268. };
  71269. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71270. /**
  71271. * Fired when the A button on this controller is modified
  71272. */
  71273. get: function () {
  71274. if (this.hand === 'right') {
  71275. return this.onMainButtonStateChangedObservable;
  71276. }
  71277. else {
  71278. throw new Error('No A button on left hand');
  71279. }
  71280. },
  71281. enumerable: true,
  71282. configurable: true
  71283. });
  71284. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71285. /**
  71286. * Fired when the B button on this controller is modified
  71287. */
  71288. get: function () {
  71289. if (this.hand === 'right') {
  71290. return this.onSecondaryButtonStateChangedObservable;
  71291. }
  71292. else {
  71293. throw new Error('No B button on left hand');
  71294. }
  71295. },
  71296. enumerable: true,
  71297. configurable: true
  71298. });
  71299. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71300. /**
  71301. * Fired when the X button on this controller is modified
  71302. */
  71303. get: function () {
  71304. if (this.hand === 'left') {
  71305. return this.onMainButtonStateChangedObservable;
  71306. }
  71307. else {
  71308. throw new Error('No X button on right hand');
  71309. }
  71310. },
  71311. enumerable: true,
  71312. configurable: true
  71313. });
  71314. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71315. /**
  71316. * Fired when the Y button on this controller is modified
  71317. */
  71318. get: function () {
  71319. if (this.hand === 'left') {
  71320. return this.onSecondaryButtonStateChangedObservable;
  71321. }
  71322. else {
  71323. throw new Error('No Y button on right hand');
  71324. }
  71325. },
  71326. enumerable: true,
  71327. configurable: true
  71328. });
  71329. /**
  71330. * Called once for each button that changed state since the last frame
  71331. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71332. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71333. * 2) secondary trigger (same)
  71334. * 3) A (right) X (left), touch, pressed = value
  71335. * 4) B / Y
  71336. * 5) thumb rest
  71337. * @param buttonIdx Which button index changed
  71338. * @param state New state of the button
  71339. * @param changes Which properties on the state changed since last frame
  71340. */
  71341. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71342. var notifyObject = state; //{ state: state, changes: changes };
  71343. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71344. switch (buttonIdx) {
  71345. case 0:
  71346. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71347. return;
  71348. case 1: // index trigger
  71349. if (this._defaultModel) {
  71350. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71351. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71352. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71353. }
  71354. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71355. return;
  71356. case 2: // secondary trigger
  71357. if (this._defaultModel) {
  71358. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71359. }
  71360. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71361. return;
  71362. case 3:
  71363. if (this._defaultModel) {
  71364. if (notifyObject.pressed) {
  71365. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71366. }
  71367. else {
  71368. (this._defaultModel.getChildren()[1]).position.y = 0;
  71369. }
  71370. }
  71371. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71372. return;
  71373. case 4:
  71374. if (this._defaultModel) {
  71375. if (notifyObject.pressed) {
  71376. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71377. }
  71378. else {
  71379. (this._defaultModel.getChildren()[2]).position.y = 0;
  71380. }
  71381. }
  71382. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71383. return;
  71384. case 5:
  71385. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71386. return;
  71387. }
  71388. };
  71389. /**
  71390. * Base Url for the controller model.
  71391. */
  71392. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71393. /**
  71394. * File name for the left controller model.
  71395. */
  71396. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71397. /**
  71398. * File name for the right controller model.
  71399. */
  71400. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71401. return OculusTouchController;
  71402. }(BABYLON.WebVRController));
  71403. BABYLON.OculusTouchController = OculusTouchController;
  71404. })(BABYLON || (BABYLON = {}));
  71405. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71406. var BABYLON;
  71407. (function (BABYLON) {
  71408. /**
  71409. * Vive Controller
  71410. */
  71411. var ViveController = /** @class */ (function (_super) {
  71412. __extends(ViveController, _super);
  71413. /**
  71414. * Creates a new ViveController from a gamepad
  71415. * @param vrGamepad the gamepad that the controller should be created from
  71416. */
  71417. function ViveController(vrGamepad) {
  71418. var _this = _super.call(this, vrGamepad) || this;
  71419. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  71420. _this._invertLeftStickY = true;
  71421. return _this;
  71422. }
  71423. /**
  71424. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71425. * @param scene scene in which to add meshes
  71426. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71427. */
  71428. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71429. var _this = this;
  71430. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  71431. /*
  71432. Parent Mesh name: ViveWand
  71433. - body
  71434. - r_gripper
  71435. - l_gripper
  71436. - menu_button
  71437. - system_button
  71438. - trackpad
  71439. - trigger
  71440. - LED
  71441. */
  71442. _this._defaultModel = newMeshes[1];
  71443. _this.attachToMesh(_this._defaultModel);
  71444. if (meshLoaded) {
  71445. meshLoaded(_this._defaultModel);
  71446. }
  71447. });
  71448. };
  71449. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  71450. /**
  71451. * Fired when the left button on this controller is modified
  71452. */
  71453. get: function () {
  71454. return this.onMainButtonStateChangedObservable;
  71455. },
  71456. enumerable: true,
  71457. configurable: true
  71458. });
  71459. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  71460. /**
  71461. * Fired when the right button on this controller is modified
  71462. */
  71463. get: function () {
  71464. return this.onMainButtonStateChangedObservable;
  71465. },
  71466. enumerable: true,
  71467. configurable: true
  71468. });
  71469. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  71470. /**
  71471. * Fired when the menu button on this controller is modified
  71472. */
  71473. get: function () {
  71474. return this.onSecondaryButtonStateChangedObservable;
  71475. },
  71476. enumerable: true,
  71477. configurable: true
  71478. });
  71479. /**
  71480. * Called once for each button that changed state since the last frame
  71481. * Vive mapping:
  71482. * 0: touchpad
  71483. * 1: trigger
  71484. * 2: left AND right buttons
  71485. * 3: menu button
  71486. * @param buttonIdx Which button index changed
  71487. * @param state New state of the button
  71488. * @param changes Which properties on the state changed since last frame
  71489. */
  71490. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71491. var notifyObject = state; //{ state: state, changes: changes };
  71492. switch (buttonIdx) {
  71493. case 0:
  71494. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71495. return;
  71496. case 1: // index trigger
  71497. if (this._defaultModel) {
  71498. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  71499. }
  71500. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71501. return;
  71502. case 2: // left AND right button
  71503. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71504. return;
  71505. case 3:
  71506. if (this._defaultModel) {
  71507. if (notifyObject.pressed) {
  71508. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71509. }
  71510. else {
  71511. (this._defaultModel.getChildren()[2]).position.y = 0;
  71512. }
  71513. }
  71514. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71515. return;
  71516. }
  71517. };
  71518. /**
  71519. * Base Url for the controller model.
  71520. */
  71521. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  71522. /**
  71523. * File name for the controller model.
  71524. */
  71525. ViveController.MODEL_FILENAME = 'wand.babylon';
  71526. return ViveController;
  71527. }(BABYLON.WebVRController));
  71528. BABYLON.ViveController = ViveController;
  71529. })(BABYLON || (BABYLON = {}));
  71530. //# sourceMappingURL=babylon.viveController.js.map
  71531. var BABYLON;
  71532. (function (BABYLON) {
  71533. /**
  71534. * Generic Controller
  71535. */
  71536. var GenericController = /** @class */ (function (_super) {
  71537. __extends(GenericController, _super);
  71538. /**
  71539. * Creates a new GenericController from a gamepad
  71540. * @param vrGamepad the gamepad that the controller should be created from
  71541. */
  71542. function GenericController(vrGamepad) {
  71543. return _super.call(this, vrGamepad) || this;
  71544. }
  71545. /**
  71546. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71547. * @param scene scene in which to add meshes
  71548. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71549. */
  71550. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71551. var _this = this;
  71552. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  71553. _this._defaultModel = newMeshes[1];
  71554. _this.attachToMesh(_this._defaultModel);
  71555. if (meshLoaded) {
  71556. meshLoaded(_this._defaultModel);
  71557. }
  71558. });
  71559. };
  71560. /**
  71561. * Called once for each button that changed state since the last frame
  71562. * @param buttonIdx Which button index changed
  71563. * @param state New state of the button
  71564. * @param changes Which properties on the state changed since last frame
  71565. */
  71566. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71567. console.log("Button id: " + buttonIdx + "state: ");
  71568. console.dir(state);
  71569. };
  71570. /**
  71571. * Base Url for the controller model.
  71572. */
  71573. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71574. /**
  71575. * File name for the controller model.
  71576. */
  71577. GenericController.MODEL_FILENAME = 'generic.babylon';
  71578. return GenericController;
  71579. }(BABYLON.WebVRController));
  71580. BABYLON.GenericController = GenericController;
  71581. })(BABYLON || (BABYLON = {}));
  71582. //# sourceMappingURL=babylon.genericController.js.map
  71583. var BABYLON;
  71584. (function (BABYLON) {
  71585. /**
  71586. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  71587. */
  71588. var LoadedMeshInfo = /** @class */ (function () {
  71589. function LoadedMeshInfo() {
  71590. /**
  71591. * Map of the button meshes contained in the controller
  71592. */
  71593. this.buttonMeshes = {};
  71594. /**
  71595. * Map of the axis meshes contained in the controller
  71596. */
  71597. this.axisMeshes = {};
  71598. }
  71599. return LoadedMeshInfo;
  71600. }());
  71601. /**
  71602. * Defines the WindowsMotionController object that the state of the windows motion controller
  71603. */
  71604. var WindowsMotionController = /** @class */ (function (_super) {
  71605. __extends(WindowsMotionController, _super);
  71606. /**
  71607. * Creates a new WindowsMotionController from a gamepad
  71608. * @param vrGamepad the gamepad that the controller should be created from
  71609. */
  71610. function WindowsMotionController(vrGamepad) {
  71611. var _this = _super.call(this, vrGamepad) || this;
  71612. _this._mapping = {
  71613. // Semantic button names
  71614. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  71615. // A mapping of the button name to glTF model node name
  71616. // that should be transformed by button value.
  71617. buttonMeshNames: {
  71618. 'trigger': 'SELECT',
  71619. 'menu': 'MENU',
  71620. 'grip': 'GRASP',
  71621. 'thumbstick': 'THUMBSTICK_PRESS',
  71622. 'trackpad': 'TOUCHPAD_PRESS'
  71623. },
  71624. // This mapping is used to translate from the Motion Controller to Babylon semantics
  71625. buttonObservableNames: {
  71626. 'trigger': 'onTriggerStateChangedObservable',
  71627. 'menu': 'onSecondaryButtonStateChangedObservable',
  71628. 'grip': 'onMainButtonStateChangedObservable',
  71629. 'thumbstick': 'onPadStateChangedObservable',
  71630. 'trackpad': 'onTrackpadChangedObservable'
  71631. },
  71632. // A mapping of the axis name to glTF model node name
  71633. // that should be transformed by axis value.
  71634. // This array mirrors the browserGamepad.axes array, such that
  71635. // the mesh corresponding to axis 0 is in this array index 0.
  71636. axisMeshNames: [
  71637. 'THUMBSTICK_X',
  71638. 'THUMBSTICK_Y',
  71639. 'TOUCHPAD_TOUCH_X',
  71640. 'TOUCHPAD_TOUCH_Y'
  71641. ],
  71642. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  71643. };
  71644. /**
  71645. * Fired when the trackpad on this controller is clicked
  71646. */
  71647. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  71648. /**
  71649. * Fired when the trackpad on this controller is modified
  71650. */
  71651. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  71652. /**
  71653. * The current x and y values of this controller's trackpad
  71654. */
  71655. _this.trackpad = { x: 0, y: 0 };
  71656. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  71657. _this._loadedMeshInfo = null;
  71658. return _this;
  71659. }
  71660. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  71661. /**
  71662. * Fired when the trigger on this controller is modified
  71663. */
  71664. get: function () {
  71665. return this.onTriggerStateChangedObservable;
  71666. },
  71667. enumerable: true,
  71668. configurable: true
  71669. });
  71670. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  71671. /**
  71672. * Fired when the menu button on this controller is modified
  71673. */
  71674. get: function () {
  71675. return this.onSecondaryButtonStateChangedObservable;
  71676. },
  71677. enumerable: true,
  71678. configurable: true
  71679. });
  71680. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  71681. /**
  71682. * Fired when the grip button on this controller is modified
  71683. */
  71684. get: function () {
  71685. return this.onMainButtonStateChangedObservable;
  71686. },
  71687. enumerable: true,
  71688. configurable: true
  71689. });
  71690. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  71691. /**
  71692. * Fired when the thumbstick button on this controller is modified
  71693. */
  71694. get: function () {
  71695. return this.onPadStateChangedObservable;
  71696. },
  71697. enumerable: true,
  71698. configurable: true
  71699. });
  71700. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  71701. /**
  71702. * Fired when the touchpad button on this controller is modified
  71703. */
  71704. get: function () {
  71705. return this.onTrackpadChangedObservable;
  71706. },
  71707. enumerable: true,
  71708. configurable: true
  71709. });
  71710. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  71711. /**
  71712. * Fired when the touchpad values on this controller are modified
  71713. */
  71714. get: function () {
  71715. return this.onTrackpadValuesChangedObservable;
  71716. },
  71717. enumerable: true,
  71718. configurable: true
  71719. });
  71720. WindowsMotionController.prototype._updateTrackpad = function () {
  71721. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  71722. this.trackpad.x = this.browserGamepad["axes"][2];
  71723. this.trackpad.y = this.browserGamepad["axes"][3];
  71724. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  71725. }
  71726. };
  71727. /**
  71728. * Called once per frame by the engine.
  71729. */
  71730. WindowsMotionController.prototype.update = function () {
  71731. _super.prototype.update.call(this);
  71732. if (this.browserGamepad.axes) {
  71733. this._updateTrackpad();
  71734. // Only need to animate axes if there is a loaded mesh
  71735. if (this._loadedMeshInfo) {
  71736. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  71737. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  71738. }
  71739. }
  71740. }
  71741. };
  71742. /**
  71743. * Called once for each button that changed state since the last frame
  71744. * @param buttonIdx Which button index changed
  71745. * @param state New state of the button
  71746. * @param changes Which properties on the state changed since last frame
  71747. */
  71748. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71749. var buttonName = this._mapping.buttons[buttonIdx];
  71750. if (!buttonName) {
  71751. return;
  71752. }
  71753. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  71754. this._updateTrackpad();
  71755. // Only emit events for buttons that we know how to map from index to name
  71756. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  71757. if (observable) {
  71758. observable.notifyObservers(state);
  71759. }
  71760. this._lerpButtonTransform(buttonName, state.value);
  71761. };
  71762. /**
  71763. * Moves the buttons on the controller mesh based on their current state
  71764. * @param buttonName the name of the button to move
  71765. * @param buttonValue the value of the button which determines the buttons new position
  71766. */
  71767. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  71768. // If there is no loaded mesh, there is nothing to transform.
  71769. if (!this._loadedMeshInfo) {
  71770. return;
  71771. }
  71772. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  71773. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71774. return;
  71775. }
  71776. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  71777. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  71778. };
  71779. /**
  71780. * Moves the axis on the controller mesh based on its current state
  71781. * @param axis the index of the axis
  71782. * @param axisValue the value of the axis which determines the meshes new position
  71783. * @hidden
  71784. */
  71785. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  71786. if (!this._loadedMeshInfo) {
  71787. return;
  71788. }
  71789. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  71790. if (!meshInfo) {
  71791. return;
  71792. }
  71793. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71794. return;
  71795. }
  71796. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  71797. var lerpValue = axisValue * 0.5 + 0.5;
  71798. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  71799. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  71800. };
  71801. /**
  71802. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71803. * @param scene scene in which to add meshes
  71804. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71805. */
  71806. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  71807. var _this = this;
  71808. if (forceDefault === void 0) { forceDefault = false; }
  71809. var path;
  71810. var filename;
  71811. // Checking if GLB loader is present
  71812. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  71813. // Determine the device specific folder based on the ID suffix
  71814. var device = 'default';
  71815. if (this.id && !forceDefault) {
  71816. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  71817. device = ((match && match[0]) || device);
  71818. }
  71819. // Hand
  71820. if (this.hand === 'left') {
  71821. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  71822. }
  71823. else { // Right is the default if no hand is specified
  71824. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  71825. }
  71826. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  71827. }
  71828. else {
  71829. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  71830. path = BABYLON.GenericController.MODEL_BASE_URL;
  71831. filename = BABYLON.GenericController.MODEL_FILENAME;
  71832. }
  71833. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  71834. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  71835. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  71836. if (!_this._loadedMeshInfo) {
  71837. return;
  71838. }
  71839. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  71840. _this.attachToMesh(_this._defaultModel);
  71841. if (meshLoaded) {
  71842. meshLoaded(_this._defaultModel);
  71843. }
  71844. }, null, function (scene, message) {
  71845. BABYLON.Tools.Log(message);
  71846. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  71847. if (!forceDefault) {
  71848. _this.initControllerMesh(scene, meshLoaded, true);
  71849. }
  71850. });
  71851. };
  71852. /**
  71853. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  71854. * can be transformed by button presses and axes values, based on this._mapping.
  71855. *
  71856. * @param scene scene in which the meshes exist
  71857. * @param meshes list of meshes that make up the controller model to process
  71858. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  71859. */
  71860. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  71861. var loadedMeshInfo = null;
  71862. // Create a new mesh to contain the glTF hierarchy
  71863. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  71864. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  71865. var childMesh = null;
  71866. for (var i = 0; i < meshes.length; i++) {
  71867. var mesh = meshes[i];
  71868. if (!mesh.parent) {
  71869. // Exclude controller meshes from picking results
  71870. mesh.isPickable = false;
  71871. // Handle root node, attach to the new parentMesh
  71872. childMesh = mesh;
  71873. break;
  71874. }
  71875. }
  71876. if (childMesh) {
  71877. childMesh.setParent(parentMesh);
  71878. // Create our mesh info. Note that this method will always return non-null.
  71879. loadedMeshInfo = this.createMeshInfo(parentMesh);
  71880. }
  71881. else {
  71882. BABYLON.Tools.Warn('Could not find root node in model file.');
  71883. }
  71884. return loadedMeshInfo;
  71885. };
  71886. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  71887. var loadedMeshInfo = new LoadedMeshInfo();
  71888. var i;
  71889. loadedMeshInfo.rootNode = rootNode;
  71890. // Reset the caches
  71891. loadedMeshInfo.buttonMeshes = {};
  71892. loadedMeshInfo.axisMeshes = {};
  71893. // Button Meshes
  71894. for (i = 0; i < this._mapping.buttons.length; i++) {
  71895. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  71896. if (!buttonMeshName) {
  71897. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  71898. continue;
  71899. }
  71900. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  71901. if (!buttonMesh) {
  71902. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  71903. continue;
  71904. }
  71905. var buttonMeshInfo = {
  71906. index: i,
  71907. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  71908. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  71909. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  71910. };
  71911. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  71912. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  71913. }
  71914. else {
  71915. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  71916. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  71917. '(VALUE: ' + !!buttonMeshInfo.value +
  71918. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  71919. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  71920. ')');
  71921. }
  71922. }
  71923. // Axis Meshes
  71924. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  71925. var axisMeshName = this._mapping.axisMeshNames[i];
  71926. if (!axisMeshName) {
  71927. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  71928. continue;
  71929. }
  71930. var axisMesh = getChildByName(rootNode, axisMeshName);
  71931. if (!axisMesh) {
  71932. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  71933. continue;
  71934. }
  71935. var axisMeshInfo = {
  71936. index: i,
  71937. value: getImmediateChildByName(axisMesh, 'VALUE'),
  71938. min: getImmediateChildByName(axisMesh, 'MIN'),
  71939. max: getImmediateChildByName(axisMesh, 'MAX')
  71940. };
  71941. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  71942. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  71943. }
  71944. else {
  71945. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  71946. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  71947. '(VALUE: ' + !!axisMeshInfo.value +
  71948. ', MIN: ' + !!axisMeshInfo.min +
  71949. ', MAX:' + !!axisMeshInfo.max +
  71950. ')');
  71951. }
  71952. }
  71953. // Pointing Ray
  71954. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  71955. if (!loadedMeshInfo.pointingPoseNode) {
  71956. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  71957. }
  71958. else {
  71959. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  71960. }
  71961. return loadedMeshInfo;
  71962. // Look through all children recursively. This will return null if no mesh exists with the given name.
  71963. function getChildByName(node, name) {
  71964. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  71965. }
  71966. // Look through only immediate children. This will return null if no mesh exists with the given name.
  71967. function getImmediateChildByName(node, name) {
  71968. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  71969. }
  71970. };
  71971. /**
  71972. * Gets the ray of the controller in the direction the controller is pointing
  71973. * @param length the length the resulting ray should be
  71974. * @returns a ray in the direction the controller is pointing
  71975. */
  71976. WindowsMotionController.prototype.getForwardRay = function (length) {
  71977. if (length === void 0) { length = 100; }
  71978. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  71979. return _super.prototype.getForwardRay.call(this, length);
  71980. }
  71981. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  71982. var origin = m.getTranslation();
  71983. var forward = new BABYLON.Vector3(0, 0, -1);
  71984. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71985. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71986. return new BABYLON.Ray(origin, direction, length);
  71987. };
  71988. /**
  71989. * Disposes of the controller
  71990. */
  71991. WindowsMotionController.prototype.dispose = function () {
  71992. _super.prototype.dispose.call(this);
  71993. this.onTrackpadChangedObservable.clear();
  71994. };
  71995. /**
  71996. * The base url used to load the left and right controller models
  71997. */
  71998. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  71999. /**
  72000. * The name of the left controller model file
  72001. */
  72002. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72003. /**
  72004. * The name of the right controller model file
  72005. */
  72006. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72007. /**
  72008. * The controller name prefix for this controller type
  72009. */
  72010. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72011. /**
  72012. * The controller id pattern for this controller type
  72013. */
  72014. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72015. return WindowsMotionController;
  72016. }(BABYLON.WebVRController));
  72017. BABYLON.WindowsMotionController = WindowsMotionController;
  72018. })(BABYLON || (BABYLON = {}));
  72019. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72020. var BABYLON;
  72021. (function (BABYLON) {
  72022. /**
  72023. * Gear VR Controller
  72024. */
  72025. var GearVRController = /** @class */ (function (_super) {
  72026. __extends(GearVRController, _super);
  72027. /**
  72028. * Creates a new GearVRController from a gamepad
  72029. * @param vrGamepad the gamepad that the controller should be created from
  72030. */
  72031. function GearVRController(vrGamepad) {
  72032. var _this = _super.call(this, vrGamepad) || this;
  72033. _this._buttonIndexToObservableNameMap = [
  72034. 'onTrackpadChangedObservable',
  72035. 'onTriggerStateChangedObservable' // Trigger
  72036. ];
  72037. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72038. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  72039. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  72040. return _this;
  72041. }
  72042. /**
  72043. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72044. * @param scene scene in which to add meshes
  72045. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72046. */
  72047. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72048. var _this = this;
  72049. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72050. _this._defaultModel = newMeshes[1];
  72051. _this.attachToMesh(_this._defaultModel);
  72052. if (meshLoaded) {
  72053. meshLoaded(_this._defaultModel);
  72054. }
  72055. });
  72056. };
  72057. /**
  72058. * Called once for each button that changed state since the last frame
  72059. * @param buttonIdx Which button index changed
  72060. * @param state New state of the button
  72061. * @param changes Which properties on the state changed since last frame
  72062. */
  72063. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72064. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72065. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72066. // Only emit events for buttons that we know how to map from index to observable
  72067. var observable = this[observableName];
  72068. if (observable) {
  72069. observable.notifyObservers(state);
  72070. }
  72071. }
  72072. };
  72073. /**
  72074. * Base Url for the controller model.
  72075. */
  72076. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72077. /**
  72078. * File name for the controller model.
  72079. */
  72080. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72081. /**
  72082. * Gamepad Id prefix used to identify this controller.
  72083. */
  72084. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72085. return GearVRController;
  72086. }(BABYLON.WebVRController));
  72087. BABYLON.GearVRController = GearVRController;
  72088. })(BABYLON || (BABYLON = {}));
  72089. //# sourceMappingURL=babylon.gearVRController.js.map
  72090. var BABYLON;
  72091. (function (BABYLON) {
  72092. /**
  72093. * Google Daydream controller
  72094. */
  72095. var DaydreamController = /** @class */ (function (_super) {
  72096. __extends(DaydreamController, _super);
  72097. /**
  72098. * Creates a new DaydreamController from a gamepad
  72099. * @param vrGamepad the gamepad that the controller should be created from
  72100. */
  72101. function DaydreamController(vrGamepad) {
  72102. var _this = _super.call(this, vrGamepad) || this;
  72103. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72104. return _this;
  72105. }
  72106. /**
  72107. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72108. * @param scene scene in which to add meshes
  72109. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72110. */
  72111. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72112. var _this = this;
  72113. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72114. _this._defaultModel = newMeshes[1];
  72115. _this.attachToMesh(_this._defaultModel);
  72116. if (meshLoaded) {
  72117. meshLoaded(_this._defaultModel);
  72118. }
  72119. });
  72120. };
  72121. /**
  72122. * Called once for each button that changed state since the last frame
  72123. * @param buttonIdx Which button index changed
  72124. * @param state New state of the button
  72125. * @param changes Which properties on the state changed since last frame
  72126. */
  72127. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72128. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72129. if (buttonIdx === 0) {
  72130. var observable = this.onTriggerStateChangedObservable;
  72131. if (observable) {
  72132. observable.notifyObservers(state);
  72133. }
  72134. }
  72135. else {
  72136. // If the app or home buttons are ever made available
  72137. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72138. }
  72139. };
  72140. /**
  72141. * Base Url for the controller model.
  72142. */
  72143. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72144. /**
  72145. * File name for the controller model.
  72146. */
  72147. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72148. /**
  72149. * Gamepad Id prefix used to identify Daydream Controller.
  72150. */
  72151. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72152. return DaydreamController;
  72153. }(BABYLON.WebVRController));
  72154. BABYLON.DaydreamController = DaydreamController;
  72155. })(BABYLON || (BABYLON = {}));
  72156. //# sourceMappingURL=babylon.daydreamController.js.map
  72157. var BABYLON;
  72158. (function (BABYLON) {
  72159. var FollowCamera = /** @class */ (function (_super) {
  72160. __extends(FollowCamera, _super);
  72161. function FollowCamera(name, position, scene, lockedTarget) {
  72162. if (lockedTarget === void 0) { lockedTarget = null; }
  72163. var _this = _super.call(this, name, position, scene) || this;
  72164. _this.radius = 12;
  72165. _this.rotationOffset = 0;
  72166. _this.heightOffset = 4;
  72167. _this.cameraAcceleration = 0.05;
  72168. _this.maxCameraSpeed = 20;
  72169. _this.lockedTarget = lockedTarget;
  72170. return _this;
  72171. }
  72172. FollowCamera.prototype.getRadians = function (degrees) {
  72173. return degrees * Math.PI / 180;
  72174. };
  72175. FollowCamera.prototype.follow = function (cameraTarget) {
  72176. if (!cameraTarget)
  72177. return;
  72178. var yRotation;
  72179. if (cameraTarget.rotationQuaternion) {
  72180. var rotMatrix = new BABYLON.Matrix();
  72181. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72182. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72183. }
  72184. else {
  72185. yRotation = cameraTarget.rotation.y;
  72186. }
  72187. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72188. var targetPosition = cameraTarget.getAbsolutePosition();
  72189. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72190. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72191. var dx = targetX - this.position.x;
  72192. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72193. var dz = (targetZ) - this.position.z;
  72194. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72195. var vy = dy * this.cameraAcceleration;
  72196. var vz = dz * this.cameraAcceleration * 2;
  72197. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72198. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72199. }
  72200. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72201. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72202. }
  72203. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72204. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72205. }
  72206. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72207. this.setTarget(targetPosition);
  72208. };
  72209. FollowCamera.prototype._checkInputs = function () {
  72210. _super.prototype._checkInputs.call(this);
  72211. if (this.lockedTarget) {
  72212. this.follow(this.lockedTarget);
  72213. }
  72214. };
  72215. FollowCamera.prototype.getClassName = function () {
  72216. return "FollowCamera";
  72217. };
  72218. __decorate([
  72219. BABYLON.serialize()
  72220. ], FollowCamera.prototype, "radius", void 0);
  72221. __decorate([
  72222. BABYLON.serialize()
  72223. ], FollowCamera.prototype, "rotationOffset", void 0);
  72224. __decorate([
  72225. BABYLON.serialize()
  72226. ], FollowCamera.prototype, "heightOffset", void 0);
  72227. __decorate([
  72228. BABYLON.serialize()
  72229. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72230. __decorate([
  72231. BABYLON.serialize()
  72232. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72233. __decorate([
  72234. BABYLON.serializeAsMeshReference("lockedTargetId")
  72235. ], FollowCamera.prototype, "lockedTarget", void 0);
  72236. return FollowCamera;
  72237. }(BABYLON.TargetCamera));
  72238. BABYLON.FollowCamera = FollowCamera;
  72239. var ArcFollowCamera = /** @class */ (function (_super) {
  72240. __extends(ArcFollowCamera, _super);
  72241. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72242. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72243. _this.alpha = alpha;
  72244. _this.beta = beta;
  72245. _this.radius = radius;
  72246. _this.target = target;
  72247. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72248. _this.follow();
  72249. return _this;
  72250. }
  72251. ArcFollowCamera.prototype.follow = function () {
  72252. if (!this.target) {
  72253. return;
  72254. }
  72255. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72256. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72257. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72258. var targetPosition = this.target.getAbsolutePosition();
  72259. this.position = targetPosition.add(this._cartesianCoordinates);
  72260. this.setTarget(targetPosition);
  72261. };
  72262. ArcFollowCamera.prototype._checkInputs = function () {
  72263. _super.prototype._checkInputs.call(this);
  72264. this.follow();
  72265. };
  72266. ArcFollowCamera.prototype.getClassName = function () {
  72267. return "ArcFollowCamera";
  72268. };
  72269. return ArcFollowCamera;
  72270. }(BABYLON.TargetCamera));
  72271. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72272. })(BABYLON || (BABYLON = {}));
  72273. //# sourceMappingURL=babylon.followCamera.js.map
  72274. var BABYLON;
  72275. (function (BABYLON) {
  72276. // We're mainly based on the logic defined into the FreeCamera code
  72277. var UniversalCamera = /** @class */ (function (_super) {
  72278. __extends(UniversalCamera, _super);
  72279. //-- end properties for backward compatibility for inputs
  72280. function UniversalCamera(name, position, scene) {
  72281. var _this = _super.call(this, name, position, scene) || this;
  72282. _this.inputs.addGamepad();
  72283. return _this;
  72284. }
  72285. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72286. //-- Begin properties for backward compatibility for inputs
  72287. get: function () {
  72288. var gamepad = this.inputs.attached["gamepad"];
  72289. if (gamepad)
  72290. return gamepad.gamepadAngularSensibility;
  72291. return 0;
  72292. },
  72293. set: function (value) {
  72294. var gamepad = this.inputs.attached["gamepad"];
  72295. if (gamepad)
  72296. gamepad.gamepadAngularSensibility = value;
  72297. },
  72298. enumerable: true,
  72299. configurable: true
  72300. });
  72301. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72302. get: function () {
  72303. var gamepad = this.inputs.attached["gamepad"];
  72304. if (gamepad)
  72305. return gamepad.gamepadMoveSensibility;
  72306. return 0;
  72307. },
  72308. set: function (value) {
  72309. var gamepad = this.inputs.attached["gamepad"];
  72310. if (gamepad)
  72311. gamepad.gamepadMoveSensibility = value;
  72312. },
  72313. enumerable: true,
  72314. configurable: true
  72315. });
  72316. UniversalCamera.prototype.getClassName = function () {
  72317. return "UniversalCamera";
  72318. };
  72319. return UniversalCamera;
  72320. }(BABYLON.TouchCamera));
  72321. BABYLON.UniversalCamera = UniversalCamera;
  72322. })(BABYLON || (BABYLON = {}));
  72323. //# sourceMappingURL=babylon.universalCamera.js.map
  72324. var BABYLON;
  72325. (function (BABYLON) {
  72326. // We're mainly based on the logic defined into the FreeCamera code
  72327. var GamepadCamera = /** @class */ (function (_super) {
  72328. __extends(GamepadCamera, _super);
  72329. //-- end properties for backward compatibility for inputs
  72330. function GamepadCamera(name, position, scene) {
  72331. return _super.call(this, name, position, scene) || this;
  72332. }
  72333. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72334. //-- Begin properties for backward compatibility for inputs
  72335. get: function () {
  72336. var gamepad = this.inputs.attached["gamepad"];
  72337. if (gamepad)
  72338. return gamepad.gamepadAngularSensibility;
  72339. return 0;
  72340. },
  72341. set: function (value) {
  72342. var gamepad = this.inputs.attached["gamepad"];
  72343. if (gamepad)
  72344. gamepad.gamepadAngularSensibility = value;
  72345. },
  72346. enumerable: true,
  72347. configurable: true
  72348. });
  72349. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72350. get: function () {
  72351. var gamepad = this.inputs.attached["gamepad"];
  72352. if (gamepad)
  72353. return gamepad.gamepadMoveSensibility;
  72354. return 0;
  72355. },
  72356. set: function (value) {
  72357. var gamepad = this.inputs.attached["gamepad"];
  72358. if (gamepad)
  72359. gamepad.gamepadMoveSensibility = value;
  72360. },
  72361. enumerable: true,
  72362. configurable: true
  72363. });
  72364. GamepadCamera.prototype.getClassName = function () {
  72365. return "GamepadCamera";
  72366. };
  72367. return GamepadCamera;
  72368. }(BABYLON.UniversalCamera));
  72369. BABYLON.GamepadCamera = GamepadCamera;
  72370. })(BABYLON || (BABYLON = {}));
  72371. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72372. var BABYLON;
  72373. (function (BABYLON) {
  72374. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72375. function PostProcessRenderPipelineManager() {
  72376. this._renderPipelines = {};
  72377. }
  72378. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72379. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72380. };
  72381. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72382. if (unique === void 0) { unique = false; }
  72383. var renderPipeline = this._renderPipelines[renderPipelineName];
  72384. if (!renderPipeline) {
  72385. return;
  72386. }
  72387. renderPipeline._attachCameras(cameras, unique);
  72388. };
  72389. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72390. var renderPipeline = this._renderPipelines[renderPipelineName];
  72391. if (!renderPipeline) {
  72392. return;
  72393. }
  72394. renderPipeline._detachCameras(cameras);
  72395. };
  72396. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72397. var renderPipeline = this._renderPipelines[renderPipelineName];
  72398. if (!renderPipeline) {
  72399. return;
  72400. }
  72401. renderPipeline._enableEffect(renderEffectName, cameras);
  72402. };
  72403. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72404. var renderPipeline = this._renderPipelines[renderPipelineName];
  72405. if (!renderPipeline) {
  72406. return;
  72407. }
  72408. renderPipeline._disableEffect(renderEffectName, cameras);
  72409. };
  72410. PostProcessRenderPipelineManager.prototype.update = function () {
  72411. for (var renderPipelineName in this._renderPipelines) {
  72412. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72413. var pipeline = this._renderPipelines[renderPipelineName];
  72414. if (!pipeline.isSupported) {
  72415. pipeline.dispose();
  72416. delete this._renderPipelines[renderPipelineName];
  72417. }
  72418. else {
  72419. pipeline._update();
  72420. }
  72421. }
  72422. }
  72423. };
  72424. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72425. for (var renderPipelineName in this._renderPipelines) {
  72426. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72427. var pipeline = this._renderPipelines[renderPipelineName];
  72428. pipeline._rebuild();
  72429. }
  72430. }
  72431. };
  72432. PostProcessRenderPipelineManager.prototype.dispose = function () {
  72433. for (var renderPipelineName in this._renderPipelines) {
  72434. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72435. var pipeline = this._renderPipelines[renderPipelineName];
  72436. pipeline.dispose();
  72437. }
  72438. }
  72439. };
  72440. return PostProcessRenderPipelineManager;
  72441. }());
  72442. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  72443. })(BABYLON || (BABYLON = {}));
  72444. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  72445. var BABYLON;
  72446. (function (BABYLON) {
  72447. /**
  72448. * This represents a set of one or more post processes in Babylon.
  72449. * A post process can be used to apply a shader to a texture after it is rendered.
  72450. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  72451. */
  72452. var PostProcessRenderEffect = /** @class */ (function () {
  72453. /**
  72454. * Instantiates a post process render effect.
  72455. * A post process can be used to apply a shader to a texture after it is rendered.
  72456. * @param engine The engine the effect is tied to
  72457. * @param name The name of the effect
  72458. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  72459. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  72460. */
  72461. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  72462. this._name = name;
  72463. this._singleInstance = singleInstance || true;
  72464. this._getPostProcesses = getPostProcesses;
  72465. this._cameras = {};
  72466. this._indicesForCamera = {};
  72467. this._postProcesses = {};
  72468. }
  72469. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  72470. /**
  72471. * Checks if all the post processes in the effect are supported.
  72472. */
  72473. get: function () {
  72474. for (var index in this._postProcesses) {
  72475. if (this._postProcesses.hasOwnProperty(index)) {
  72476. var pps = this._postProcesses[index];
  72477. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  72478. if (!pps[ppIndex].isSupported) {
  72479. return false;
  72480. }
  72481. }
  72482. }
  72483. }
  72484. return true;
  72485. },
  72486. enumerable: true,
  72487. configurable: true
  72488. });
  72489. /**
  72490. * Updates the current state of the effect
  72491. */
  72492. PostProcessRenderEffect.prototype._update = function () {
  72493. };
  72494. /**
  72495. * Attaches the effect on cameras
  72496. * @param cameras The camera to attach to.
  72497. */
  72498. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  72499. var _this = this;
  72500. var cameraKey;
  72501. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72502. if (!cams) {
  72503. return;
  72504. }
  72505. for (var i = 0; i < cams.length; i++) {
  72506. var camera = cams[i];
  72507. var cameraName = camera.name;
  72508. if (this._singleInstance) {
  72509. cameraKey = 0;
  72510. }
  72511. else {
  72512. cameraKey = cameraName;
  72513. }
  72514. if (!this._postProcesses[cameraKey]) {
  72515. var postProcess = this._getPostProcesses();
  72516. if (postProcess) {
  72517. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  72518. }
  72519. }
  72520. if (!this._indicesForCamera[cameraName]) {
  72521. this._indicesForCamera[cameraName] = [];
  72522. }
  72523. this._postProcesses[cameraKey].forEach(function (postProcess) {
  72524. var index = camera.attachPostProcess(postProcess);
  72525. _this._indicesForCamera[cameraName].push(index);
  72526. });
  72527. if (!this._cameras[cameraName]) {
  72528. this._cameras[cameraName] = camera;
  72529. }
  72530. }
  72531. };
  72532. /**
  72533. * Detatches the effect on cameras
  72534. * @param cameras The camera to detatch from.
  72535. */
  72536. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  72537. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72538. if (!cams) {
  72539. return;
  72540. }
  72541. for (var i = 0; i < cams.length; i++) {
  72542. var camera = cams[i];
  72543. var cameraName = camera.name;
  72544. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72545. camera.detachPostProcess(postProcess);
  72546. });
  72547. if (this._cameras[cameraName]) {
  72548. //this._indicesForCamera.splice(index, 1);
  72549. this._cameras[cameraName] = null;
  72550. }
  72551. }
  72552. };
  72553. /**
  72554. * Enables the effect on given cameras
  72555. * @param cameras The camera to enable.
  72556. */
  72557. PostProcessRenderEffect.prototype._enable = function (cameras) {
  72558. var _this = this;
  72559. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72560. if (!cams) {
  72561. return;
  72562. }
  72563. for (var i = 0; i < cams.length; i++) {
  72564. var camera = cams[i];
  72565. var cameraName = camera.name;
  72566. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  72567. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  72568. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72569. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  72570. });
  72571. }
  72572. }
  72573. }
  72574. };
  72575. /**
  72576. * Disables the effect on the given cameras
  72577. * @param cameras The camera to disable.
  72578. */
  72579. PostProcessRenderEffect.prototype._disable = function (cameras) {
  72580. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72581. if (!cams) {
  72582. return;
  72583. }
  72584. for (var i = 0; i < cams.length; i++) {
  72585. var camera = cams[i];
  72586. var cameraName = camera.name;
  72587. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72588. camera.detachPostProcess(postProcess);
  72589. });
  72590. }
  72591. };
  72592. /**
  72593. * Gets a list of the post processes contained in the effect.
  72594. * @param camera The camera to get the post processes on.
  72595. * @returns The list of the post processes in the effect.
  72596. */
  72597. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  72598. if (this._singleInstance) {
  72599. return this._postProcesses[0];
  72600. }
  72601. else {
  72602. if (!camera) {
  72603. return null;
  72604. }
  72605. return this._postProcesses[camera.name];
  72606. }
  72607. };
  72608. return PostProcessRenderEffect;
  72609. }());
  72610. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  72611. })(BABYLON || (BABYLON = {}));
  72612. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  72613. var BABYLON;
  72614. (function (BABYLON) {
  72615. var PostProcessRenderPipeline = /** @class */ (function () {
  72616. function PostProcessRenderPipeline(engine, name) {
  72617. this.engine = engine;
  72618. this._name = name;
  72619. this._renderEffects = {};
  72620. this._renderEffectsForIsolatedPass = new Array();
  72621. this._cameras = [];
  72622. }
  72623. PostProcessRenderPipeline.prototype.getClassName = function () {
  72624. return "PostProcessRenderPipeline";
  72625. };
  72626. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  72627. get: function () {
  72628. for (var renderEffectName in this._renderEffects) {
  72629. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72630. if (!this._renderEffects[renderEffectName].isSupported) {
  72631. return false;
  72632. }
  72633. }
  72634. }
  72635. return true;
  72636. },
  72637. enumerable: true,
  72638. configurable: true
  72639. });
  72640. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  72641. this._renderEffects[renderEffect._name] = renderEffect;
  72642. };
  72643. // private
  72644. PostProcessRenderPipeline.prototype._rebuild = function () {
  72645. };
  72646. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  72647. var renderEffects = this._renderEffects[renderEffectName];
  72648. if (!renderEffects) {
  72649. return;
  72650. }
  72651. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72652. };
  72653. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  72654. var renderEffects = this._renderEffects[renderEffectName];
  72655. if (!renderEffects) {
  72656. return;
  72657. }
  72658. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72659. };
  72660. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  72661. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72662. if (!cams) {
  72663. return;
  72664. }
  72665. var indicesToDelete = [];
  72666. var i;
  72667. for (i = 0; i < cams.length; i++) {
  72668. var camera = cams[i];
  72669. var cameraName = camera.name;
  72670. if (this._cameras.indexOf(camera) === -1) {
  72671. this._cameras[cameraName] = camera;
  72672. }
  72673. else if (unique) {
  72674. indicesToDelete.push(i);
  72675. }
  72676. }
  72677. for (i = 0; i < indicesToDelete.length; i++) {
  72678. cameras.splice(indicesToDelete[i], 1);
  72679. }
  72680. for (var renderEffectName in this._renderEffects) {
  72681. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72682. this._renderEffects[renderEffectName]._attachCameras(cams);
  72683. }
  72684. }
  72685. };
  72686. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  72687. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72688. if (!cams) {
  72689. return;
  72690. }
  72691. for (var renderEffectName in this._renderEffects) {
  72692. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72693. this._renderEffects[renderEffectName]._detachCameras(cams);
  72694. }
  72695. }
  72696. for (var i = 0; i < cams.length; i++) {
  72697. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  72698. }
  72699. };
  72700. PostProcessRenderPipeline.prototype._update = function () {
  72701. for (var renderEffectName in this._renderEffects) {
  72702. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72703. this._renderEffects[renderEffectName]._update();
  72704. }
  72705. }
  72706. for (var i = 0; i < this._cameras.length; i++) {
  72707. var cameraName = this._cameras[i].name;
  72708. if (this._renderEffectsForIsolatedPass[cameraName]) {
  72709. this._renderEffectsForIsolatedPass[cameraName]._update();
  72710. }
  72711. }
  72712. };
  72713. PostProcessRenderPipeline.prototype._reset = function () {
  72714. this._renderEffects = {};
  72715. this._renderEffectsForIsolatedPass = new Array();
  72716. };
  72717. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  72718. // 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)
  72719. var effectKeys = Object.keys(this._renderEffects);
  72720. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  72721. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  72722. if (postProcesses) {
  72723. postProcesses[0].samples = sampleCount;
  72724. return true;
  72725. }
  72726. }
  72727. return false;
  72728. };
  72729. PostProcessRenderPipeline.prototype.dispose = function () {
  72730. // Must be implemented by children
  72731. };
  72732. __decorate([
  72733. BABYLON.serialize()
  72734. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  72735. return PostProcessRenderPipeline;
  72736. }());
  72737. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  72738. })(BABYLON || (BABYLON = {}));
  72739. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  72740. var BABYLON;
  72741. (function (BABYLON) {
  72742. /**
  72743. * This represents a depth renderer in Babylon.
  72744. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  72745. */
  72746. var DepthRenderer = /** @class */ (function () {
  72747. /**
  72748. * Instantiates a depth renderer
  72749. * @param scene The scene the renderer belongs to
  72750. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  72751. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  72752. */
  72753. function DepthRenderer(scene, type, camera) {
  72754. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72755. if (camera === void 0) { camera = null; }
  72756. var _this = this;
  72757. this._scene = scene;
  72758. this._camera = camera;
  72759. var engine = scene.getEngine();
  72760. // Render target
  72761. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  72762. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72763. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72764. this._depthMap.refreshRate = 1;
  72765. this._depthMap.renderParticles = false;
  72766. this._depthMap.renderList = null;
  72767. // Camera to get depth map from to support multiple concurrent cameras
  72768. this._depthMap.activeCamera = this._camera;
  72769. this._depthMap.ignoreCameraViewport = true;
  72770. this._depthMap.useCameraPostProcesses = false;
  72771. // set default depth value to 1.0 (far away)
  72772. this._depthMap.onClearObservable.add(function (engine) {
  72773. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  72774. });
  72775. // Custom render function
  72776. var renderSubMesh = function (subMesh) {
  72777. var mesh = subMesh.getRenderingMesh();
  72778. var scene = _this._scene;
  72779. var engine = scene.getEngine();
  72780. var material = subMesh.getMaterial();
  72781. if (!material) {
  72782. return;
  72783. }
  72784. // Culling and reverse (right handed system)
  72785. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  72786. // Managing instances
  72787. var batch = mesh._getInstancesRenderList(subMesh._id);
  72788. if (batch.mustReturn) {
  72789. return;
  72790. }
  72791. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  72792. var camera = _this._camera || scene.activeCamera;
  72793. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  72794. engine.enableEffect(_this._effect);
  72795. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  72796. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  72797. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  72798. // Alpha test
  72799. if (material && material.needAlphaTesting()) {
  72800. var alphaTexture = material.getAlphaTestTexture();
  72801. if (alphaTexture) {
  72802. _this._effect.setTexture("diffuseSampler", alphaTexture);
  72803. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72804. }
  72805. }
  72806. // Bones
  72807. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72808. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72809. }
  72810. // Draw
  72811. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72812. }
  72813. };
  72814. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72815. var index;
  72816. if (depthOnlySubMeshes.length) {
  72817. engine.setColorWrite(false);
  72818. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72819. renderSubMesh(depthOnlySubMeshes.data[index]);
  72820. }
  72821. engine.setColorWrite(true);
  72822. }
  72823. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72824. renderSubMesh(opaqueSubMeshes.data[index]);
  72825. }
  72826. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72827. renderSubMesh(alphaTestSubMeshes.data[index]);
  72828. }
  72829. };
  72830. }
  72831. /**
  72832. * Creates the depth rendering effect and checks if the effect is ready.
  72833. * @param subMesh The submesh to be used to render the depth map of
  72834. * @param useInstances If multiple world instances should be used
  72835. * @returns if the depth renderer is ready to render the depth map
  72836. */
  72837. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  72838. var material = subMesh.getMaterial();
  72839. if (material.disableDepthWrite) {
  72840. return false;
  72841. }
  72842. var defines = [];
  72843. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72844. var mesh = subMesh.getMesh();
  72845. // Alpha test
  72846. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  72847. defines.push("#define ALPHATEST");
  72848. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72849. attribs.push(BABYLON.VertexBuffer.UVKind);
  72850. defines.push("#define UV1");
  72851. }
  72852. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72853. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72854. defines.push("#define UV2");
  72855. }
  72856. }
  72857. // Bones
  72858. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72859. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72860. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72861. if (mesh.numBoneInfluencers > 4) {
  72862. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72863. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72864. }
  72865. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72866. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  72867. }
  72868. else {
  72869. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72870. }
  72871. // Instances
  72872. if (useInstances) {
  72873. defines.push("#define INSTANCES");
  72874. attribs.push("world0");
  72875. attribs.push("world1");
  72876. attribs.push("world2");
  72877. attribs.push("world3");
  72878. }
  72879. // Get correct effect
  72880. var join = defines.join("\n");
  72881. if (this._cachedDefines !== join) {
  72882. this._cachedDefines = join;
  72883. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  72884. }
  72885. return this._effect.isReady();
  72886. };
  72887. /**
  72888. * Gets the texture which the depth map will be written to.
  72889. * @returns The depth map texture
  72890. */
  72891. DepthRenderer.prototype.getDepthMap = function () {
  72892. return this._depthMap;
  72893. };
  72894. /**
  72895. * Disposes of the depth renderer.
  72896. */
  72897. DepthRenderer.prototype.dispose = function () {
  72898. this._depthMap.dispose();
  72899. };
  72900. return DepthRenderer;
  72901. }());
  72902. BABYLON.DepthRenderer = DepthRenderer;
  72903. })(BABYLON || (BABYLON = {}));
  72904. //# sourceMappingURL=babylon.depthRenderer.js.map
  72905. var BABYLON;
  72906. (function (BABYLON) {
  72907. var SSAORenderingPipeline = /** @class */ (function (_super) {
  72908. __extends(SSAORenderingPipeline, _super);
  72909. /**
  72910. * @constructor
  72911. * @param {string} name - The rendering pipeline name
  72912. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72913. * @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 }
  72914. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72915. */
  72916. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  72917. var _this = _super.call(this, scene.getEngine(), name) || this;
  72918. // Members
  72919. /**
  72920. * The PassPostProcess id in the pipeline that contains the original scene color
  72921. */
  72922. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  72923. /**
  72924. * The SSAO PostProcess id in the pipeline
  72925. */
  72926. _this.SSAORenderEffect = "SSAORenderEffect";
  72927. /**
  72928. * The horizontal blur PostProcess id in the pipeline
  72929. */
  72930. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  72931. /**
  72932. * The vertical blur PostProcess id in the pipeline
  72933. */
  72934. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  72935. /**
  72936. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  72937. */
  72938. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  72939. /**
  72940. * The output strength of the SSAO post-process. Default value is 1.0.
  72941. */
  72942. _this.totalStrength = 1.0;
  72943. /**
  72944. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  72945. */
  72946. _this.radius = 0.0001;
  72947. /**
  72948. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  72949. * Must not be equal to fallOff and superior to fallOff.
  72950. * Default value is 0.975
  72951. */
  72952. _this.area = 0.0075;
  72953. /**
  72954. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  72955. * Must not be equal to area and inferior to area.
  72956. * Default value is 0.0
  72957. */
  72958. _this.fallOff = 0.000001;
  72959. /**
  72960. * The base color of the SSAO post-process
  72961. * The final result is "base + ssao" between [0, 1]
  72962. */
  72963. _this.base = 0.5;
  72964. _this._firstUpdate = true;
  72965. _this._scene = scene;
  72966. // Set up assets
  72967. _this._createRandomTexture();
  72968. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  72969. var ssaoRatio = ratio.ssaoRatio || ratio;
  72970. var combineRatio = ratio.combineRatio || ratio;
  72971. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  72972. _this._createSSAOPostProcess(ssaoRatio);
  72973. _this._createBlurPostProcess(ssaoRatio);
  72974. _this._createSSAOCombinePostProcess(combineRatio);
  72975. // Set up pipeline
  72976. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  72977. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  72978. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  72979. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  72980. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  72981. // Finish
  72982. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72983. if (cameras)
  72984. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72985. return _this;
  72986. }
  72987. // Public Methods
  72988. /**
  72989. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  72990. */
  72991. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  72992. if (disableDepthRender === void 0) { disableDepthRender = false; }
  72993. for (var i = 0; i < this._scene.cameras.length; i++) {
  72994. var camera = this._scene.cameras[i];
  72995. this._originalColorPostProcess.dispose(camera);
  72996. this._ssaoPostProcess.dispose(camera);
  72997. this._blurHPostProcess.dispose(camera);
  72998. this._blurVPostProcess.dispose(camera);
  72999. this._ssaoCombinePostProcess.dispose(camera);
  73000. }
  73001. this._randomTexture.dispose();
  73002. if (disableDepthRender)
  73003. this._scene.disableDepthRenderer();
  73004. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73005. _super.prototype.dispose.call(this);
  73006. };
  73007. // Private Methods
  73008. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73009. var _this = this;
  73010. var size = 16;
  73011. 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);
  73012. 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);
  73013. this._blurHPostProcess.onActivateObservable.add(function () {
  73014. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73015. _this._blurHPostProcess.kernel = size * dw;
  73016. });
  73017. this._blurVPostProcess.onActivateObservable.add(function () {
  73018. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73019. _this._blurVPostProcess.kernel = size * dw;
  73020. });
  73021. };
  73022. SSAORenderingPipeline.prototype._rebuild = function () {
  73023. this._firstUpdate = true;
  73024. _super.prototype._rebuild.call(this);
  73025. };
  73026. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73027. var _this = this;
  73028. var numSamples = 16;
  73029. var sampleSphere = [
  73030. 0.5381, 0.1856, -0.4319,
  73031. 0.1379, 0.2486, 0.4430,
  73032. 0.3371, 0.5679, -0.0057,
  73033. -0.6999, -0.0451, -0.0019,
  73034. 0.0689, -0.1598, -0.8547,
  73035. 0.0560, 0.0069, -0.1843,
  73036. -0.0146, 0.1402, 0.0762,
  73037. 0.0100, -0.1924, -0.0344,
  73038. -0.3577, -0.5301, -0.4358,
  73039. -0.3169, 0.1063, 0.0158,
  73040. 0.0103, -0.5869, 0.0046,
  73041. -0.0897, -0.4940, 0.3287,
  73042. 0.7119, -0.0154, -0.0918,
  73043. -0.0533, 0.0596, -0.5411,
  73044. 0.0352, -0.0631, 0.5460,
  73045. -0.4776, 0.2847, -0.0271
  73046. ];
  73047. var samplesFactor = 1.0 / numSamples;
  73048. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73049. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73050. "area", "fallOff", "base", "range", "viewport"
  73051. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73052. this._ssaoPostProcess.onApply = function (effect) {
  73053. if (_this._firstUpdate) {
  73054. effect.setArray3("sampleSphere", sampleSphere);
  73055. effect.setFloat("samplesFactor", samplesFactor);
  73056. effect.setFloat("randTextureTiles", 4.0);
  73057. }
  73058. effect.setFloat("totalStrength", _this.totalStrength);
  73059. effect.setFloat("radius", _this.radius);
  73060. effect.setFloat("area", _this.area);
  73061. effect.setFloat("fallOff", _this.fallOff);
  73062. effect.setFloat("base", _this.base);
  73063. effect.setTexture("textureSampler", _this._depthTexture);
  73064. effect.setTexture("randomSampler", _this._randomTexture);
  73065. };
  73066. };
  73067. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73068. var _this = this;
  73069. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73070. this._ssaoCombinePostProcess.onApply = function (effect) {
  73071. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  73072. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73073. };
  73074. };
  73075. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73076. var size = 512;
  73077. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73078. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73079. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73080. var context = this._randomTexture.getContext();
  73081. var rand = function (min, max) {
  73082. return Math.random() * (max - min) + min;
  73083. };
  73084. var randVector = BABYLON.Vector3.Zero();
  73085. for (var x = 0; x < size; x++) {
  73086. for (var y = 0; y < size; y++) {
  73087. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73088. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73089. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73090. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73091. context.fillRect(x, y, 1, 1);
  73092. }
  73093. }
  73094. this._randomTexture.update(false);
  73095. };
  73096. __decorate([
  73097. BABYLON.serialize()
  73098. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73099. __decorate([
  73100. BABYLON.serialize()
  73101. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73102. __decorate([
  73103. BABYLON.serialize()
  73104. ], SSAORenderingPipeline.prototype, "area", void 0);
  73105. __decorate([
  73106. BABYLON.serialize()
  73107. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73108. __decorate([
  73109. BABYLON.serialize()
  73110. ], SSAORenderingPipeline.prototype, "base", void 0);
  73111. return SSAORenderingPipeline;
  73112. }(BABYLON.PostProcessRenderPipeline));
  73113. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73114. })(BABYLON || (BABYLON = {}));
  73115. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73116. var BABYLON;
  73117. (function (BABYLON) {
  73118. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73119. __extends(SSAO2RenderingPipeline, _super);
  73120. /**
  73121. * @constructor
  73122. * @param {string} name - The rendering pipeline name
  73123. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73124. * @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 }
  73125. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73126. */
  73127. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73128. var _this = _super.call(this, scene.getEngine(), name) || this;
  73129. // Members
  73130. /**
  73131. * The PassPostProcess id in the pipeline that contains the original scene color
  73132. */
  73133. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73134. /**
  73135. * The SSAO PostProcess id in the pipeline
  73136. */
  73137. _this.SSAORenderEffect = "SSAORenderEffect";
  73138. /**
  73139. * The horizontal blur PostProcess id in the pipeline
  73140. */
  73141. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73142. /**
  73143. * The vertical blur PostProcess id in the pipeline
  73144. */
  73145. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73146. /**
  73147. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73148. */
  73149. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73150. /**
  73151. * The output strength of the SSAO post-process. Default value is 1.0.
  73152. */
  73153. _this.totalStrength = 1.0;
  73154. /**
  73155. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73156. */
  73157. _this.maxZ = 100.0;
  73158. /**
  73159. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73160. */
  73161. _this.minZAspect = 0.2;
  73162. /**
  73163. * Number of samples used for the SSAO calculations. Default value is 8
  73164. */
  73165. _this._samples = 8;
  73166. /**
  73167. * Are we using bilateral blur ?
  73168. */
  73169. _this._expensiveBlur = true;
  73170. /**
  73171. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73172. */
  73173. _this.radius = 2.0;
  73174. /**
  73175. * The base color of the SSAO post-process
  73176. * The final result is "base + ssao" between [0, 1]
  73177. */
  73178. _this.base = 0.1;
  73179. _this._firstUpdate = true;
  73180. _this._scene = scene;
  73181. _this._ratio = ratio;
  73182. if (!_this.isSupported) {
  73183. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73184. return _this;
  73185. }
  73186. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73187. var blurRatio = _this._ratio.blurRatio || ratio;
  73188. // Set up assets
  73189. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73190. _this._createRandomTexture();
  73191. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73192. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73193. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73194. _this._createSSAOPostProcess(1.0);
  73195. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73196. _this._createSSAOCombinePostProcess(blurRatio);
  73197. // Set up pipeline
  73198. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73199. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73200. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73201. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73202. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73203. // Finish
  73204. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73205. if (cameras)
  73206. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73207. return _this;
  73208. }
  73209. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73210. get: function () {
  73211. return this._samples;
  73212. },
  73213. set: function (n) {
  73214. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73215. this._samples = n;
  73216. this._sampleSphere = this._generateHemisphere();
  73217. this._firstUpdate = true;
  73218. },
  73219. enumerable: true,
  73220. configurable: true
  73221. });
  73222. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73223. get: function () {
  73224. return this._expensiveBlur;
  73225. },
  73226. set: function (b) {
  73227. 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"]);
  73228. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73229. this._expensiveBlur = b;
  73230. this._firstUpdate = true;
  73231. },
  73232. enumerable: true,
  73233. configurable: true
  73234. });
  73235. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73236. /**
  73237. * Support test.
  73238. */
  73239. get: function () {
  73240. var engine = BABYLON.Engine.LastCreatedEngine;
  73241. if (!engine) {
  73242. return false;
  73243. }
  73244. return engine.getCaps().drawBuffersExtension;
  73245. },
  73246. enumerable: true,
  73247. configurable: true
  73248. });
  73249. // Public Methods
  73250. /**
  73251. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73252. */
  73253. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73254. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73255. for (var i = 0; i < this._scene.cameras.length; i++) {
  73256. var camera = this._scene.cameras[i];
  73257. this._originalColorPostProcess.dispose(camera);
  73258. this._ssaoPostProcess.dispose(camera);
  73259. this._blurHPostProcess.dispose(camera);
  73260. this._blurVPostProcess.dispose(camera);
  73261. this._ssaoCombinePostProcess.dispose(camera);
  73262. }
  73263. this._randomTexture.dispose();
  73264. if (disableGeometryBufferRenderer)
  73265. this._scene.disableGeometryBufferRenderer();
  73266. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73267. _super.prototype.dispose.call(this);
  73268. };
  73269. // Private Methods
  73270. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73271. var _this = this;
  73272. this._samplerOffsets = [];
  73273. var expensive = this.expensiveBlur;
  73274. for (var i = -8; i < 8; i++) {
  73275. this._samplerOffsets.push(i * 2 + 0.5);
  73276. }
  73277. 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");
  73278. this._blurHPostProcess.onApply = function (effect) {
  73279. if (!_this._scene.activeCamera) {
  73280. return;
  73281. }
  73282. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73283. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73284. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73285. effect.setFloat("radius", _this.radius);
  73286. effect.setTexture("depthSampler", _this._depthTexture);
  73287. if (_this._firstUpdate) {
  73288. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73289. }
  73290. };
  73291. 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");
  73292. this._blurVPostProcess.onApply = function (effect) {
  73293. if (!_this._scene.activeCamera) {
  73294. return;
  73295. }
  73296. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73297. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73298. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73299. effect.setFloat("radius", _this.radius);
  73300. effect.setTexture("depthSampler", _this._depthTexture);
  73301. if (_this._firstUpdate) {
  73302. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73303. _this._firstUpdate = false;
  73304. }
  73305. };
  73306. };
  73307. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73308. this._firstUpdate = true;
  73309. _super.prototype._rebuild.call(this);
  73310. };
  73311. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73312. var numSamples = this.samples;
  73313. var result = [];
  73314. var vector, scale;
  73315. var rand = function (min, max) {
  73316. return Math.random() * (max - min) + min;
  73317. };
  73318. var i = 0;
  73319. while (i < numSamples) {
  73320. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73321. vector.normalize();
  73322. scale = i / numSamples;
  73323. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73324. vector.scaleInPlace(scale);
  73325. result.push(vector.x, vector.y, vector.z);
  73326. i++;
  73327. }
  73328. return result;
  73329. };
  73330. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73331. var _this = this;
  73332. var numSamples = this.samples;
  73333. this._sampleSphere = this._generateHemisphere();
  73334. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73335. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73336. "base", "range", "projection", "near", "far", "texelSize",
  73337. "xViewport", "yViewport", "maxZ", "minZAspect"
  73338. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73339. this._ssaoPostProcess.onApply = function (effect) {
  73340. if (_this._firstUpdate) {
  73341. effect.setArray3("sampleSphere", _this._sampleSphere);
  73342. effect.setFloat("randTextureTiles", 4.0);
  73343. }
  73344. if (!_this._scene.activeCamera) {
  73345. return;
  73346. }
  73347. effect.setFloat("samplesFactor", 1 / _this.samples);
  73348. effect.setFloat("totalStrength", _this.totalStrength);
  73349. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73350. effect.setFloat("radius", _this.radius);
  73351. effect.setFloat("maxZ", _this.maxZ);
  73352. effect.setFloat("minZAspect", _this.minZAspect);
  73353. effect.setFloat("base", _this.base);
  73354. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73355. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73356. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73357. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73358. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73359. effect.setTexture("textureSampler", _this._depthTexture);
  73360. effect.setTexture("normalSampler", _this._normalTexture);
  73361. effect.setTexture("randomSampler", _this._randomTexture);
  73362. };
  73363. };
  73364. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73365. var _this = this;
  73366. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73367. this._ssaoCombinePostProcess.onApply = function (effect) {
  73368. var viewport = _this._scene.activeCamera.viewport;
  73369. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  73370. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73371. };
  73372. };
  73373. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73374. var size = 512;
  73375. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73376. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73377. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73378. var context = this._randomTexture.getContext();
  73379. var rand = function (min, max) {
  73380. return Math.random() * (max - min) + min;
  73381. };
  73382. var randVector = BABYLON.Vector3.Zero();
  73383. for (var x = 0; x < size; x++) {
  73384. for (var y = 0; y < size; y++) {
  73385. randVector.x = rand(0.0, 1.0);
  73386. randVector.y = rand(0.0, 1.0);
  73387. randVector.z = 0.0;
  73388. randVector.normalize();
  73389. randVector.scaleInPlace(255);
  73390. randVector.x = Math.floor(randVector.x);
  73391. randVector.y = Math.floor(randVector.y);
  73392. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73393. context.fillRect(x, y, 1, 1);
  73394. }
  73395. }
  73396. this._randomTexture.update(false);
  73397. };
  73398. /**
  73399. * Serialize the rendering pipeline (Used when exporting)
  73400. * @returns the serialized object
  73401. */
  73402. SSAO2RenderingPipeline.prototype.serialize = function () {
  73403. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73404. serializationObject.customType = "SSAO2RenderingPipeline";
  73405. return serializationObject;
  73406. };
  73407. /**
  73408. * Parse the serialized pipeline
  73409. * @param source Source pipeline.
  73410. * @param scene The scene to load the pipeline to.
  73411. * @param rootUrl The URL of the serialized pipeline.
  73412. * @returns An instantiated pipeline from the serialized object.
  73413. */
  73414. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  73415. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73416. };
  73417. __decorate([
  73418. BABYLON.serialize()
  73419. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73420. __decorate([
  73421. BABYLON.serialize()
  73422. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73423. __decorate([
  73424. BABYLON.serialize()
  73425. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  73426. __decorate([
  73427. BABYLON.serialize("samples")
  73428. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  73429. __decorate([
  73430. BABYLON.serialize()
  73431. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  73432. __decorate([
  73433. BABYLON.serialize("expensiveBlur")
  73434. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  73435. __decorate([
  73436. BABYLON.serialize()
  73437. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  73438. __decorate([
  73439. BABYLON.serialize()
  73440. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  73441. return SSAO2RenderingPipeline;
  73442. }(BABYLON.PostProcessRenderPipeline));
  73443. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  73444. })(BABYLON || (BABYLON = {}));
  73445. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  73446. // BABYLON.JS Chromatic Aberration GLSL Shader
  73447. // Author: Olivier Guyot
  73448. // Separates very slightly R, G and B colors on the edges of the screen
  73449. // Inspired by Francois Tarlier & Martins Upitis
  73450. var BABYLON;
  73451. (function (BABYLON) {
  73452. var LensRenderingPipeline = /** @class */ (function (_super) {
  73453. __extends(LensRenderingPipeline, _super);
  73454. /**
  73455. * @constructor
  73456. *
  73457. * Effect parameters are as follow:
  73458. * {
  73459. * chromatic_aberration: number; // from 0 to x (1 for realism)
  73460. * edge_blur: number; // from 0 to x (1 for realism)
  73461. * distortion: number; // from 0 to x (1 for realism)
  73462. * grain_amount: number; // from 0 to 1
  73463. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  73464. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  73465. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  73466. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  73467. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  73468. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  73469. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  73470. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  73471. * }
  73472. * Note: if an effect parameter is unset, effect is disabled
  73473. *
  73474. * @param {string} name - The rendering pipeline name
  73475. * @param {object} parameters - An object containing all parameters (see above)
  73476. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73477. * @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)
  73478. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73479. */
  73480. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  73481. if (ratio === void 0) { ratio = 1.0; }
  73482. var _this = _super.call(this, scene.getEngine(), name) || this;
  73483. // Lens effects can be of the following:
  73484. // - chromatic aberration (slight shift of RGB colors)
  73485. // - blur on the edge of the lens
  73486. // - lens distortion
  73487. // - depth-of-field blur & highlights enhancing
  73488. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  73489. // - grain effect (noise or custom texture)
  73490. // Two additional texture samplers are needed:
  73491. // - depth map (for depth-of-field)
  73492. // - grain texture
  73493. /**
  73494. * The chromatic aberration PostProcess id in the pipeline
  73495. */
  73496. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  73497. /**
  73498. * The highlights enhancing PostProcess id in the pipeline
  73499. */
  73500. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  73501. /**
  73502. * The depth-of-field PostProcess id in the pipeline
  73503. */
  73504. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  73505. _this._scene = scene;
  73506. // Fetch texture samplers
  73507. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73508. if (parameters.grain_texture) {
  73509. _this._grainTexture = parameters.grain_texture;
  73510. }
  73511. else {
  73512. _this._createGrainTexture();
  73513. }
  73514. // save parameters
  73515. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  73516. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  73517. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  73518. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  73519. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  73520. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  73521. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  73522. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  73523. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  73524. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  73525. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  73526. // Create effects
  73527. _this._createChromaticAberrationPostProcess(ratio);
  73528. _this._createHighlightsPostProcess(ratio);
  73529. _this._createDepthOfFieldPostProcess(ratio / 4);
  73530. // Set up pipeline
  73531. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  73532. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  73533. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  73534. if (_this._highlightsGain === -1) {
  73535. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  73536. }
  73537. // Finish
  73538. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73539. if (cameras) {
  73540. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73541. }
  73542. return _this;
  73543. }
  73544. // public methods (self explanatory)
  73545. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  73546. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  73547. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  73548. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  73549. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  73550. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  73551. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  73552. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  73553. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  73554. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  73555. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  73556. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  73557. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  73558. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  73559. };
  73560. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  73561. this._highlightsPostProcess.updateEffect();
  73562. };
  73563. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  73564. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  73565. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  73566. this._highlightsGain = amount;
  73567. };
  73568. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  73569. if (this._highlightsGain === -1) {
  73570. this._highlightsGain = 1.0;
  73571. }
  73572. this._highlightsThreshold = amount;
  73573. };
  73574. LensRenderingPipeline.prototype.disableHighlights = function () {
  73575. this._highlightsGain = -1;
  73576. };
  73577. /**
  73578. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  73579. */
  73580. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73581. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73582. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73583. this._chromaticAberrationPostProcess = null;
  73584. this._highlightsPostProcess = null;
  73585. this._depthOfFieldPostProcess = null;
  73586. this._grainTexture.dispose();
  73587. if (disableDepthRender)
  73588. this._scene.disableDepthRenderer();
  73589. };
  73590. // colors shifting and distortion
  73591. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  73592. var _this = this;
  73593. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  73594. [], // samplers
  73595. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73596. this._chromaticAberrationPostProcess.onApply = function (effect) {
  73597. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  73598. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73599. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73600. effect.setFloat('radialIntensity', 1);
  73601. effect.setFloat2('direction', 17, 17);
  73602. effect.setFloat2('centerPosition', 0.5, 0.5);
  73603. };
  73604. };
  73605. // highlights enhancing
  73606. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  73607. var _this = this;
  73608. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  73609. [], // samplers
  73610. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  73611. this._highlightsPostProcess.onApply = function (effect) {
  73612. effect.setFloat('gain', _this._highlightsGain);
  73613. effect.setFloat('threshold', _this._highlightsThreshold);
  73614. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  73615. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73616. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73617. };
  73618. };
  73619. // colors shifting and distortion
  73620. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  73621. var _this = this;
  73622. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  73623. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  73624. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  73625. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73626. this._depthOfFieldPostProcess.onApply = function (effect) {
  73627. effect.setTexture("depthSampler", _this._depthTexture);
  73628. effect.setTexture("grainSampler", _this._grainTexture);
  73629. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  73630. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  73631. effect.setFloat('grain_amount', _this._grainAmount);
  73632. effect.setBool('blur_noise', _this._blurNoise);
  73633. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73634. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73635. effect.setFloat('distortion', _this._distortion);
  73636. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  73637. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  73638. effect.setFloat('aperture', _this._dofAperture);
  73639. effect.setFloat('darken', _this._dofDarken);
  73640. effect.setFloat('edge_blur', _this._edgeBlur);
  73641. effect.setBool('highlights', (_this._highlightsGain !== -1));
  73642. if (_this._scene.activeCamera) {
  73643. effect.setFloat('near', _this._scene.activeCamera.minZ);
  73644. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  73645. }
  73646. };
  73647. };
  73648. // creates a black and white random noise texture, 512x512
  73649. LensRenderingPipeline.prototype._createGrainTexture = function () {
  73650. var size = 512;
  73651. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73652. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73653. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73654. var context = this._grainTexture.getContext();
  73655. var rand = function (min, max) {
  73656. return Math.random() * (max - min) + min;
  73657. };
  73658. var value;
  73659. for (var x = 0; x < size; x++) {
  73660. for (var y = 0; y < size; y++) {
  73661. value = Math.floor(rand(0.42, 0.58) * 255);
  73662. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  73663. context.fillRect(x, y, 1, 1);
  73664. }
  73665. }
  73666. this._grainTexture.update(false);
  73667. };
  73668. return LensRenderingPipeline;
  73669. }(BABYLON.PostProcessRenderPipeline));
  73670. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  73671. })(BABYLON || (BABYLON = {}));
  73672. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  73673. var BABYLON;
  73674. (function (BABYLON) {
  73675. var StandardRenderingPipeline = /** @class */ (function (_super) {
  73676. __extends(StandardRenderingPipeline, _super);
  73677. /**
  73678. * @constructor
  73679. * @param {string} name - The rendering pipeline name
  73680. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73681. * @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)
  73682. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  73683. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73684. */
  73685. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  73686. if (originalPostProcess === void 0) { originalPostProcess = null; }
  73687. var _this = _super.call(this, scene.getEngine(), name) || this;
  73688. _this.downSampleX4PostProcess = null;
  73689. _this.brightPassPostProcess = null;
  73690. _this.blurHPostProcesses = [];
  73691. _this.blurVPostProcesses = [];
  73692. _this.textureAdderPostProcess = null;
  73693. _this.volumetricLightPostProcess = null;
  73694. _this.volumetricLightSmoothXPostProcess = null;
  73695. _this.volumetricLightSmoothYPostProcess = null;
  73696. _this.volumetricLightMergePostProces = null;
  73697. _this.volumetricLightFinalPostProcess = null;
  73698. _this.luminancePostProcess = null;
  73699. _this.luminanceDownSamplePostProcesses = [];
  73700. _this.hdrPostProcess = null;
  73701. _this.textureAdderFinalPostProcess = null;
  73702. _this.lensFlareFinalPostProcess = null;
  73703. _this.hdrFinalPostProcess = null;
  73704. _this.lensFlarePostProcess = null;
  73705. _this.lensFlareComposePostProcess = null;
  73706. _this.motionBlurPostProcess = null;
  73707. _this.depthOfFieldPostProcess = null;
  73708. // Values
  73709. _this.brightThreshold = 1.0;
  73710. _this.blurWidth = 512.0;
  73711. _this.horizontalBlur = false;
  73712. _this.exposure = 1.0;
  73713. _this.lensTexture = null;
  73714. _this.volumetricLightCoefficient = 0.2;
  73715. _this.volumetricLightPower = 4.0;
  73716. _this.volumetricLightBlurScale = 64.0;
  73717. _this.sourceLight = null;
  73718. _this.hdrMinimumLuminance = 1.0;
  73719. _this.hdrDecreaseRate = 0.5;
  73720. _this.hdrIncreaseRate = 0.5;
  73721. _this.lensColorTexture = null;
  73722. _this.lensFlareStrength = 20.0;
  73723. _this.lensFlareGhostDispersal = 1.4;
  73724. _this.lensFlareHaloWidth = 0.7;
  73725. _this.lensFlareDistortionStrength = 16.0;
  73726. _this.lensStarTexture = null;
  73727. _this.lensFlareDirtTexture = null;
  73728. _this.depthOfFieldDistance = 10.0;
  73729. _this.depthOfFieldBlurWidth = 64.0;
  73730. _this.motionStrength = 1.0;
  73731. // IAnimatable
  73732. _this.animations = [];
  73733. _this._currentDepthOfFieldSource = null;
  73734. _this._hdrCurrentLuminance = 1.0;
  73735. // Getters and setters
  73736. _this._bloomEnabled = true;
  73737. _this._depthOfFieldEnabled = false;
  73738. _this._vlsEnabled = false;
  73739. _this._lensFlareEnabled = false;
  73740. _this._hdrEnabled = false;
  73741. _this._motionBlurEnabled = false;
  73742. _this._motionBlurSamples = 64.0;
  73743. _this._volumetricLightStepsCount = 50.0;
  73744. _this._cameras = cameras || [];
  73745. // Initialize
  73746. _this._scene = scene;
  73747. _this._basePostProcess = originalPostProcess;
  73748. _this._ratio = ratio;
  73749. // Misc
  73750. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73751. // Finish
  73752. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73753. _this._buildPipeline();
  73754. return _this;
  73755. }
  73756. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  73757. get: function () {
  73758. return this._bloomEnabled;
  73759. },
  73760. set: function (enabled) {
  73761. if (this._bloomEnabled === enabled) {
  73762. return;
  73763. }
  73764. this._bloomEnabled = enabled;
  73765. this._buildPipeline();
  73766. },
  73767. enumerable: true,
  73768. configurable: true
  73769. });
  73770. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  73771. get: function () {
  73772. return this._depthOfFieldEnabled;
  73773. },
  73774. set: function (enabled) {
  73775. if (this._depthOfFieldEnabled === enabled) {
  73776. return;
  73777. }
  73778. this._depthOfFieldEnabled = enabled;
  73779. this._buildPipeline();
  73780. },
  73781. enumerable: true,
  73782. configurable: true
  73783. });
  73784. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  73785. get: function () {
  73786. return this._lensFlareEnabled;
  73787. },
  73788. set: function (enabled) {
  73789. if (this._lensFlareEnabled === enabled) {
  73790. return;
  73791. }
  73792. this._lensFlareEnabled = enabled;
  73793. this._buildPipeline();
  73794. },
  73795. enumerable: true,
  73796. configurable: true
  73797. });
  73798. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  73799. get: function () {
  73800. return this._hdrEnabled;
  73801. },
  73802. set: function (enabled) {
  73803. if (this._hdrEnabled === enabled) {
  73804. return;
  73805. }
  73806. this._hdrEnabled = enabled;
  73807. this._buildPipeline();
  73808. },
  73809. enumerable: true,
  73810. configurable: true
  73811. });
  73812. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  73813. get: function () {
  73814. return this._vlsEnabled;
  73815. },
  73816. set: function (enabled) {
  73817. if (this._vlsEnabled === enabled) {
  73818. return;
  73819. }
  73820. if (enabled) {
  73821. var geometry = this._scene.enableGeometryBufferRenderer();
  73822. if (!geometry) {
  73823. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  73824. return;
  73825. }
  73826. }
  73827. this._vlsEnabled = enabled;
  73828. this._buildPipeline();
  73829. },
  73830. enumerable: true,
  73831. configurable: true
  73832. });
  73833. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  73834. get: function () {
  73835. return this._motionBlurEnabled;
  73836. },
  73837. set: function (enabled) {
  73838. if (this._motionBlurEnabled === enabled) {
  73839. return;
  73840. }
  73841. this._motionBlurEnabled = enabled;
  73842. this._buildPipeline();
  73843. },
  73844. enumerable: true,
  73845. configurable: true
  73846. });
  73847. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  73848. get: function () {
  73849. return this._volumetricLightStepsCount;
  73850. },
  73851. set: function (count) {
  73852. if (this.volumetricLightPostProcess) {
  73853. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  73854. }
  73855. this._volumetricLightStepsCount = count;
  73856. },
  73857. enumerable: true,
  73858. configurable: true
  73859. });
  73860. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  73861. get: function () {
  73862. return this._motionBlurSamples;
  73863. },
  73864. set: function (samples) {
  73865. if (this.motionBlurPostProcess) {
  73866. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  73867. }
  73868. this._motionBlurSamples = samples;
  73869. },
  73870. enumerable: true,
  73871. configurable: true
  73872. });
  73873. StandardRenderingPipeline.prototype._buildPipeline = function () {
  73874. var _this = this;
  73875. var ratio = this._ratio;
  73876. var scene = this._scene;
  73877. this._disposePostProcesses();
  73878. this._reset();
  73879. // Create pass post-process
  73880. if (!this._basePostProcess) {
  73881. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  73882. this.originalPostProcess.onApply = function (effect) {
  73883. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  73884. };
  73885. }
  73886. else {
  73887. this.originalPostProcess = this._basePostProcess;
  73888. }
  73889. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  73890. this._currentDepthOfFieldSource = this.originalPostProcess;
  73891. if (this._bloomEnabled) {
  73892. // Create down sample X4 post-process
  73893. this._createDownSampleX4PostProcess(scene, ratio / 2);
  73894. // Create bright pass post-process
  73895. this._createBrightPassPostProcess(scene, ratio / 2);
  73896. // Create gaussian blur post-processes (down sampling blurs)
  73897. this._createBlurPostProcesses(scene, ratio / 4, 1);
  73898. // Create texture adder post-process
  73899. this._createTextureAdderPostProcess(scene, ratio);
  73900. // Create depth-of-field source post-process
  73901. 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);
  73902. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  73903. }
  73904. if (this._vlsEnabled) {
  73905. // Create volumetric light
  73906. this._createVolumetricLightPostProcess(scene, ratio);
  73907. // Create volumetric light final post-process
  73908. 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);
  73909. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  73910. }
  73911. if (this._lensFlareEnabled) {
  73912. // Create lens flare post-process
  73913. this._createLensFlarePostProcess(scene, ratio);
  73914. // Create depth-of-field source post-process post lens-flare and disable it now
  73915. 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);
  73916. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  73917. }
  73918. if (this._hdrEnabled) {
  73919. // Create luminance
  73920. this._createLuminancePostProcesses(scene, this._floatTextureType);
  73921. // Create HDR
  73922. this._createHdrPostProcess(scene, ratio);
  73923. // Create depth-of-field source post-process post hdr and disable it now
  73924. 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);
  73925. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  73926. }
  73927. if (this._depthOfFieldEnabled) {
  73928. // Create gaussian blur used by depth-of-field
  73929. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  73930. // Create depth-of-field post-process
  73931. this._createDepthOfFieldPostProcess(scene, ratio);
  73932. }
  73933. if (this._motionBlurEnabled) {
  73934. // Create motion blur post-process
  73935. this._createMotionBlurPostProcess(scene, ratio);
  73936. }
  73937. if (this._cameras !== null) {
  73938. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  73939. }
  73940. };
  73941. // Down Sample X4 Post-Processs
  73942. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  73943. var _this = this;
  73944. var downSampleX4Offsets = new Array(32);
  73945. 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);
  73946. this.downSampleX4PostProcess.onApply = function (effect) {
  73947. var id = 0;
  73948. var width = _this.downSampleX4PostProcess.width;
  73949. var height = _this.downSampleX4PostProcess.height;
  73950. for (var i = -2; i < 2; i++) {
  73951. for (var j = -2; j < 2; j++) {
  73952. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  73953. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  73954. id += 2;
  73955. }
  73956. }
  73957. effect.setArray2("dsOffsets", downSampleX4Offsets);
  73958. };
  73959. // Add to pipeline
  73960. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  73961. };
  73962. // Brightpass Post-Process
  73963. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  73964. var _this = this;
  73965. var brightOffsets = new Array(8);
  73966. 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);
  73967. this.brightPassPostProcess.onApply = function (effect) {
  73968. var sU = (1.0 / _this.brightPassPostProcess.width);
  73969. var sV = (1.0 / _this.brightPassPostProcess.height);
  73970. brightOffsets[0] = -0.5 * sU;
  73971. brightOffsets[1] = 0.5 * sV;
  73972. brightOffsets[2] = 0.5 * sU;
  73973. brightOffsets[3] = 0.5 * sV;
  73974. brightOffsets[4] = -0.5 * sU;
  73975. brightOffsets[5] = -0.5 * sV;
  73976. brightOffsets[6] = 0.5 * sU;
  73977. brightOffsets[7] = -0.5 * sV;
  73978. effect.setArray2("dsOffsets", brightOffsets);
  73979. effect.setFloat("brightThreshold", _this.brightThreshold);
  73980. };
  73981. // Add to pipeline
  73982. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  73983. };
  73984. // Create blur H&V post-processes
  73985. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  73986. var _this = this;
  73987. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  73988. var engine = scene.getEngine();
  73989. 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);
  73990. 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);
  73991. blurX.onActivateObservable.add(function () {
  73992. var dw = blurX.width / engine.getRenderWidth();
  73993. blurX.kernel = _this[blurWidthKey] * dw;
  73994. });
  73995. blurY.onActivateObservable.add(function () {
  73996. var dw = blurY.height / engine.getRenderHeight();
  73997. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  73998. });
  73999. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74000. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74001. this.blurHPostProcesses.push(blurX);
  74002. this.blurVPostProcesses.push(blurY);
  74003. };
  74004. // Create texture adder post-process
  74005. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74006. var _this = this;
  74007. 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);
  74008. this.textureAdderPostProcess.onApply = function (effect) {
  74009. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74010. effect.setTexture("lensSampler", _this.lensTexture);
  74011. effect.setFloat("exposure", _this.exposure);
  74012. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74013. };
  74014. // Add to pipeline
  74015. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74016. };
  74017. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74018. var _this = this;
  74019. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74020. geometryRenderer.enablePosition = true;
  74021. var geometry = geometryRenderer.getGBuffer();
  74022. // Base post-process
  74023. 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));
  74024. var depthValues = BABYLON.Vector2.Zero();
  74025. this.volumetricLightPostProcess.onApply = function (effect) {
  74026. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74027. var generator = _this.sourceLight.getShadowGenerator();
  74028. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74029. effect.setTexture("positionSampler", geometry.textures[2]);
  74030. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74031. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74032. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74033. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74034. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74035. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74036. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74037. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74038. effect.setVector2("depthValues", depthValues);
  74039. }
  74040. };
  74041. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74042. // Smooth
  74043. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74044. // Merge
  74045. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74046. this.volumetricLightMergePostProces.onApply = function (effect) {
  74047. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74048. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74049. };
  74050. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74051. };
  74052. // Create luminance
  74053. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74054. var _this = this;
  74055. // Create luminance
  74056. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74057. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74058. var offsets = [];
  74059. this.luminancePostProcess.onApply = function (effect) {
  74060. var sU = (1.0 / _this.luminancePostProcess.width);
  74061. var sV = (1.0 / _this.luminancePostProcess.height);
  74062. offsets[0] = -0.5 * sU;
  74063. offsets[1] = 0.5 * sV;
  74064. offsets[2] = 0.5 * sU;
  74065. offsets[3] = 0.5 * sV;
  74066. offsets[4] = -0.5 * sU;
  74067. offsets[5] = -0.5 * sV;
  74068. offsets[6] = 0.5 * sU;
  74069. offsets[7] = -0.5 * sV;
  74070. effect.setArray2("lumOffsets", offsets);
  74071. };
  74072. // Add to pipeline
  74073. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74074. // Create down sample luminance
  74075. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74076. var size = Math.pow(3, i);
  74077. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74078. if (i === 0) {
  74079. defines += "#define FINAL_DOWN_SAMPLER";
  74080. }
  74081. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74082. this.luminanceDownSamplePostProcesses.push(postProcess);
  74083. }
  74084. // Create callbacks and add effects
  74085. var lastLuminance = this.luminancePostProcess;
  74086. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74087. var downSampleOffsets = new Array(18);
  74088. pp.onApply = function (effect) {
  74089. if (!lastLuminance) {
  74090. return;
  74091. }
  74092. var id = 0;
  74093. for (var x = -1; x < 2; x++) {
  74094. for (var y = -1; y < 2; y++) {
  74095. downSampleOffsets[id] = x / lastLuminance.width;
  74096. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74097. id += 2;
  74098. }
  74099. }
  74100. effect.setArray2("dsOffsets", downSampleOffsets);
  74101. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74102. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74103. lastLuminance = _this.luminancePostProcess;
  74104. }
  74105. else {
  74106. lastLuminance = pp;
  74107. }
  74108. };
  74109. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74110. pp.onAfterRender = function (effect) {
  74111. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74112. 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);
  74113. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74114. };
  74115. }
  74116. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74117. });
  74118. };
  74119. // Create HDR post-process
  74120. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74121. var _this = this;
  74122. 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);
  74123. var outputLiminance = 1;
  74124. var time = 0;
  74125. var lastTime = 0;
  74126. this.hdrPostProcess.onApply = function (effect) {
  74127. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74128. time += scene.getEngine().getDeltaTime();
  74129. if (outputLiminance < 0) {
  74130. outputLiminance = _this._hdrCurrentLuminance;
  74131. }
  74132. else {
  74133. var dt = (lastTime - time) / 1000.0;
  74134. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74135. outputLiminance += _this.hdrDecreaseRate * dt;
  74136. }
  74137. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74138. outputLiminance -= _this.hdrIncreaseRate * dt;
  74139. }
  74140. else {
  74141. outputLiminance = _this._hdrCurrentLuminance;
  74142. }
  74143. }
  74144. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74145. effect.setFloat("averageLuminance", outputLiminance);
  74146. lastTime = time;
  74147. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74148. };
  74149. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74150. };
  74151. // Create lens flare post-process
  74152. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74153. var _this = this;
  74154. 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);
  74155. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74156. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74157. 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);
  74158. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74159. var resolution = new BABYLON.Vector2(0, 0);
  74160. // Lens flare
  74161. this.lensFlarePostProcess.onApply = function (effect) {
  74162. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74163. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74164. effect.setFloat("strength", _this.lensFlareStrength);
  74165. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74166. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74167. // Shift
  74168. resolution.x = _this.lensFlarePostProcess.width;
  74169. resolution.y = _this.lensFlarePostProcess.height;
  74170. effect.setVector2("resolution", resolution);
  74171. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74172. };
  74173. // Compose
  74174. 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);
  74175. 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);
  74176. this.lensFlareComposePostProcess.onApply = function (effect) {
  74177. if (!_this._scene.activeCamera) {
  74178. return;
  74179. }
  74180. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74181. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74182. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74183. // Lens start rotation matrix
  74184. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74185. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74186. 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));
  74187. camRot *= 4.0;
  74188. 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);
  74189. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74190. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74191. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74192. };
  74193. };
  74194. // Create depth-of-field post-process
  74195. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74196. var _this = this;
  74197. 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);
  74198. this.depthOfFieldPostProcess.onApply = function (effect) {
  74199. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74200. effect.setTexture("depthSampler", _this._getDepthTexture());
  74201. effect.setFloat("distance", _this.depthOfFieldDistance);
  74202. };
  74203. // Add to pipeline
  74204. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74205. };
  74206. // Create motion blur post-process
  74207. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74208. var _this = this;
  74209. 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);
  74210. var motionScale = 0;
  74211. var prevViewProjection = BABYLON.Matrix.Identity();
  74212. var invViewProjection = BABYLON.Matrix.Identity();
  74213. var viewProjection = BABYLON.Matrix.Identity();
  74214. var screenSize = BABYLON.Vector2.Zero();
  74215. this.motionBlurPostProcess.onApply = function (effect) {
  74216. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74217. viewProjection.invertToRef(invViewProjection);
  74218. effect.setMatrix("inverseViewProjection", invViewProjection);
  74219. effect.setMatrix("prevViewProjection", prevViewProjection);
  74220. prevViewProjection = viewProjection;
  74221. screenSize.x = _this.motionBlurPostProcess.width;
  74222. screenSize.y = _this.motionBlurPostProcess.height;
  74223. effect.setVector2("screenSize", screenSize);
  74224. motionScale = scene.getEngine().getFps() / 60.0;
  74225. effect.setFloat("motionScale", motionScale);
  74226. effect.setFloat("motionStrength", _this.motionStrength);
  74227. effect.setTexture("depthSampler", _this._getDepthTexture());
  74228. };
  74229. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74230. };
  74231. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74232. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74233. var renderer = this._scene.enableGeometryBufferRenderer();
  74234. return renderer.getGBuffer().textures[0];
  74235. }
  74236. return this._scene.enableDepthRenderer().getDepthMap();
  74237. };
  74238. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74239. for (var i = 0; i < this._cameras.length; i++) {
  74240. var camera = this._cameras[i];
  74241. if (this.originalPostProcess) {
  74242. this.originalPostProcess.dispose(camera);
  74243. }
  74244. if (this.downSampleX4PostProcess) {
  74245. this.downSampleX4PostProcess.dispose(camera);
  74246. }
  74247. if (this.brightPassPostProcess) {
  74248. this.brightPassPostProcess.dispose(camera);
  74249. }
  74250. if (this.textureAdderPostProcess) {
  74251. this.textureAdderPostProcess.dispose(camera);
  74252. }
  74253. if (this.textureAdderFinalPostProcess) {
  74254. this.textureAdderFinalPostProcess.dispose(camera);
  74255. }
  74256. if (this.volumetricLightPostProcess) {
  74257. this.volumetricLightPostProcess.dispose(camera);
  74258. }
  74259. if (this.volumetricLightSmoothXPostProcess) {
  74260. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74261. }
  74262. if (this.volumetricLightSmoothYPostProcess) {
  74263. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74264. }
  74265. if (this.volumetricLightMergePostProces) {
  74266. this.volumetricLightMergePostProces.dispose(camera);
  74267. }
  74268. if (this.volumetricLightFinalPostProcess) {
  74269. this.volumetricLightFinalPostProcess.dispose(camera);
  74270. }
  74271. if (this.lensFlarePostProcess) {
  74272. this.lensFlarePostProcess.dispose(camera);
  74273. }
  74274. if (this.lensFlareComposePostProcess) {
  74275. this.lensFlareComposePostProcess.dispose(camera);
  74276. }
  74277. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74278. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74279. }
  74280. if (this.luminancePostProcess) {
  74281. this.luminancePostProcess.dispose(camera);
  74282. }
  74283. if (this.hdrPostProcess) {
  74284. this.hdrPostProcess.dispose(camera);
  74285. }
  74286. if (this.hdrFinalPostProcess) {
  74287. this.hdrFinalPostProcess.dispose(camera);
  74288. }
  74289. if (this.depthOfFieldPostProcess) {
  74290. this.depthOfFieldPostProcess.dispose(camera);
  74291. }
  74292. if (this.motionBlurPostProcess) {
  74293. this.motionBlurPostProcess.dispose(camera);
  74294. }
  74295. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74296. this.blurHPostProcesses[j].dispose(camera);
  74297. }
  74298. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74299. this.blurVPostProcesses[j].dispose(camera);
  74300. }
  74301. }
  74302. this.originalPostProcess = null;
  74303. this.downSampleX4PostProcess = null;
  74304. this.brightPassPostProcess = null;
  74305. this.textureAdderPostProcess = null;
  74306. this.textureAdderFinalPostProcess = null;
  74307. this.volumetricLightPostProcess = null;
  74308. this.volumetricLightSmoothXPostProcess = null;
  74309. this.volumetricLightSmoothYPostProcess = null;
  74310. this.volumetricLightMergePostProces = null;
  74311. this.volumetricLightFinalPostProcess = null;
  74312. this.lensFlarePostProcess = null;
  74313. this.lensFlareComposePostProcess = null;
  74314. this.luminancePostProcess = null;
  74315. this.hdrPostProcess = null;
  74316. this.hdrFinalPostProcess = null;
  74317. this.depthOfFieldPostProcess = null;
  74318. this.motionBlurPostProcess = null;
  74319. this.luminanceDownSamplePostProcesses = [];
  74320. this.blurHPostProcesses = [];
  74321. this.blurVPostProcesses = [];
  74322. };
  74323. /**
  74324. * Dispose of the pipeline and stop all post processes
  74325. */
  74326. StandardRenderingPipeline.prototype.dispose = function () {
  74327. this._disposePostProcesses();
  74328. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74329. _super.prototype.dispose.call(this);
  74330. };
  74331. /**
  74332. * Serialize the rendering pipeline (Used when exporting)
  74333. * @returns the serialized object
  74334. */
  74335. StandardRenderingPipeline.prototype.serialize = function () {
  74336. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74337. if (this.sourceLight) {
  74338. serializationObject.sourceLightId = this.sourceLight.id;
  74339. }
  74340. serializationObject.customType = "StandardRenderingPipeline";
  74341. return serializationObject;
  74342. };
  74343. /**
  74344. * Parse the serialized pipeline
  74345. * @param source Source pipeline.
  74346. * @param scene The scene to load the pipeline to.
  74347. * @param rootUrl The URL of the serialized pipeline.
  74348. * @returns An instantiated pipeline from the serialized object.
  74349. */
  74350. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74351. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74352. if (source.sourceLightId) {
  74353. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74354. }
  74355. return p;
  74356. };
  74357. // Luminance steps
  74358. StandardRenderingPipeline.LuminanceSteps = 6;
  74359. __decorate([
  74360. BABYLON.serialize()
  74361. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74362. __decorate([
  74363. BABYLON.serialize()
  74364. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74365. __decorate([
  74366. BABYLON.serialize()
  74367. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74368. __decorate([
  74369. BABYLON.serialize()
  74370. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74371. __decorate([
  74372. BABYLON.serializeAsTexture("lensTexture")
  74373. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74374. __decorate([
  74375. BABYLON.serialize()
  74376. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74377. __decorate([
  74378. BABYLON.serialize()
  74379. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74380. __decorate([
  74381. BABYLON.serialize()
  74382. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74383. __decorate([
  74384. BABYLON.serialize()
  74385. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74386. __decorate([
  74387. BABYLON.serialize()
  74388. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74389. __decorate([
  74390. BABYLON.serialize()
  74391. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74392. __decorate([
  74393. BABYLON.serializeAsTexture("lensColorTexture")
  74394. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74395. __decorate([
  74396. BABYLON.serialize()
  74397. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74398. __decorate([
  74399. BABYLON.serialize()
  74400. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74401. __decorate([
  74402. BABYLON.serialize()
  74403. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74404. __decorate([
  74405. BABYLON.serialize()
  74406. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74407. __decorate([
  74408. BABYLON.serializeAsTexture("lensStarTexture")
  74409. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74410. __decorate([
  74411. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74412. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74413. __decorate([
  74414. BABYLON.serialize()
  74415. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74416. __decorate([
  74417. BABYLON.serialize()
  74418. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74419. __decorate([
  74420. BABYLON.serialize()
  74421. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74422. __decorate([
  74423. BABYLON.serialize()
  74424. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74425. __decorate([
  74426. BABYLON.serialize()
  74427. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  74428. __decorate([
  74429. BABYLON.serialize()
  74430. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  74431. __decorate([
  74432. BABYLON.serialize()
  74433. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  74434. __decorate([
  74435. BABYLON.serialize()
  74436. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  74437. __decorate([
  74438. BABYLON.serialize()
  74439. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  74440. __decorate([
  74441. BABYLON.serialize()
  74442. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  74443. __decorate([
  74444. BABYLON.serialize()
  74445. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  74446. __decorate([
  74447. BABYLON.serialize()
  74448. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  74449. return StandardRenderingPipeline;
  74450. }(BABYLON.PostProcessRenderPipeline));
  74451. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  74452. })(BABYLON || (BABYLON = {}));
  74453. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  74454. var BABYLON;
  74455. (function (BABYLON) {
  74456. var FxaaPostProcess = /** @class */ (function (_super) {
  74457. __extends(FxaaPostProcess, _super);
  74458. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74459. if (camera === void 0) { camera = null; }
  74460. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74461. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  74462. var defines = _this._getDefines();
  74463. _this.updateEffect(defines);
  74464. _this.onApplyObservable.add(function (effect) {
  74465. var texelSize = _this.texelSize;
  74466. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  74467. });
  74468. return _this;
  74469. }
  74470. FxaaPostProcess.prototype._getDefines = function () {
  74471. var engine = this.getEngine();
  74472. if (!engine) {
  74473. return null;
  74474. }
  74475. var glInfo = engine.getGlInfo();
  74476. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  74477. return "#define MALI 1\n";
  74478. }
  74479. return null;
  74480. };
  74481. return FxaaPostProcess;
  74482. }(BABYLON.PostProcess));
  74483. BABYLON.FxaaPostProcess = FxaaPostProcess;
  74484. })(BABYLON || (BABYLON = {}));
  74485. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  74486. var BABYLON;
  74487. (function (BABYLON) {
  74488. /**
  74489. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  74490. */
  74491. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  74492. __extends(ChromaticAberrationPostProcess, _super);
  74493. /**
  74494. * Creates a new instance ChromaticAberrationPostProcess
  74495. * @param name The name of the effect.
  74496. * @param screenWidth The width of the screen to apply the effect on.
  74497. * @param screenHeight The height of the screen to apply the effect on.
  74498. * @param options The required width/height ratio to downsize to before computing the render pass.
  74499. * @param camera The camera to apply the render pass to.
  74500. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74501. * @param engine The engine which the post process will be applied. (default: current engine)
  74502. * @param reusable If the post process can be reused on the same frame. (default: false)
  74503. * @param textureType Type of textures used when performing the post process. (default: 0)
  74504. * @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)
  74505. */
  74506. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74507. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74508. if (blockCompilation === void 0) { blockCompilation = false; }
  74509. 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;
  74510. /**
  74511. * The amount of seperation of rgb channels (default: 30)
  74512. */
  74513. _this.aberrationAmount = 30;
  74514. /**
  74515. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  74516. */
  74517. _this.radialIntensity = 0;
  74518. /**
  74519. * 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))
  74520. */
  74521. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  74522. /**
  74523. * 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))
  74524. */
  74525. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  74526. _this.onApplyObservable.add(function (effect) {
  74527. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  74528. effect.setFloat('screen_width', screenWidth);
  74529. effect.setFloat('screen_height', screenHeight);
  74530. effect.setFloat('radialIntensity', _this.radialIntensity);
  74531. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  74532. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  74533. });
  74534. return _this;
  74535. }
  74536. return ChromaticAberrationPostProcess;
  74537. }(BABYLON.PostProcess));
  74538. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  74539. })(BABYLON || (BABYLON = {}));
  74540. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  74541. var BABYLON;
  74542. (function (BABYLON) {
  74543. /**
  74544. * The GrainPostProcess adds noise to the image at mid luminance levels
  74545. */
  74546. var GrainPostProcess = /** @class */ (function (_super) {
  74547. __extends(GrainPostProcess, _super);
  74548. /**
  74549. * Creates a new instance of @see GrainPostProcess
  74550. * @param name The name of the effect.
  74551. * @param options The required width/height ratio to downsize to before computing the render pass.
  74552. * @param camera The camera to apply the render pass to.
  74553. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74554. * @param engine The engine which the post process will be applied. (default: current engine)
  74555. * @param reusable If the post process can be reused on the same frame. (default: false)
  74556. * @param textureType Type of textures used when performing the post process. (default: 0)
  74557. * @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)
  74558. */
  74559. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74560. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74561. if (blockCompilation === void 0) { blockCompilation = false; }
  74562. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74563. /**
  74564. * The intensity of the grain added (default: 30)
  74565. */
  74566. _this.intensity = 30;
  74567. /**
  74568. * If the grain should be randomized on every frame
  74569. */
  74570. _this.animated = false;
  74571. _this.onApplyObservable.add(function (effect) {
  74572. effect.setFloat('intensity', _this.intensity);
  74573. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  74574. });
  74575. return _this;
  74576. }
  74577. return GrainPostProcess;
  74578. }(BABYLON.PostProcess));
  74579. BABYLON.GrainPostProcess = GrainPostProcess;
  74580. })(BABYLON || (BABYLON = {}));
  74581. //# sourceMappingURL=babylon.grainPostProcess.js.map
  74582. var BABYLON;
  74583. (function (BABYLON) {
  74584. /**
  74585. * The SharpenPostProcess applies a sharpen kernel to every pixel
  74586. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74587. */
  74588. var SharpenPostProcess = /** @class */ (function (_super) {
  74589. __extends(SharpenPostProcess, _super);
  74590. /**
  74591. * Creates a new instance ConvolutionPostProcess
  74592. * @param name The name of the effect.
  74593. * @param options The required width/height ratio to downsize to before computing the render pass.
  74594. * @param camera The camera to apply the render pass to.
  74595. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74596. * @param engine The engine which the post process will be applied. (default: current engine)
  74597. * @param reusable If the post process can be reused on the same frame. (default: false)
  74598. * @param textureType Type of textures used when performing the post process. (default: 0)
  74599. * @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)
  74600. */
  74601. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74602. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74603. if (blockCompilation === void 0) { blockCompilation = false; }
  74604. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74605. /**
  74606. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  74607. */
  74608. _this.colorAmount = 1.0;
  74609. /**
  74610. * How much sharpness should be applied (default: 0.3)
  74611. */
  74612. _this.edgeAmount = 0.3;
  74613. _this.onApply = function (effect) {
  74614. effect.setFloat2("screenSize", _this.width, _this.height);
  74615. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  74616. };
  74617. return _this;
  74618. }
  74619. return SharpenPostProcess;
  74620. }(BABYLON.PostProcess));
  74621. BABYLON.SharpenPostProcess = SharpenPostProcess;
  74622. })(BABYLON || (BABYLON = {}));
  74623. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  74624. var BABYLON;
  74625. (function (BABYLON) {
  74626. /**
  74627. * The Blur Post Process which blurs an image based on a kernel and direction.
  74628. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  74629. */
  74630. var BlurPostProcess = /** @class */ (function (_super) {
  74631. __extends(BlurPostProcess, _super);
  74632. /**
  74633. * Creates a new instance BlurPostProcess
  74634. * @param name The name of the effect.
  74635. * @param direction The direction in which to blur the image.
  74636. * @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.
  74637. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  74638. * @param camera The camera to apply the render pass to.
  74639. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74640. * @param engine The engine which the post process will be applied. (default: current engine)
  74641. * @param reusable If the post process can be reused on the same frame. (default: false)
  74642. * @param textureType Type of textures used when performing the post process. (default: 0)
  74643. * @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)
  74644. */
  74645. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  74646. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74647. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74648. if (defines === void 0) { defines = ""; }
  74649. if (blockCompilation === void 0) { blockCompilation = false; }
  74650. 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;
  74651. _this.direction = direction;
  74652. _this.blockCompilation = blockCompilation;
  74653. _this._packedFloat = false;
  74654. _this._staticDefines = "";
  74655. _this._staticDefines = defines;
  74656. _this.onApplyObservable.add(function (effect) {
  74657. if (_this._outputTexture) {
  74658. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  74659. }
  74660. else {
  74661. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  74662. }
  74663. });
  74664. _this.kernel = kernel;
  74665. return _this;
  74666. }
  74667. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  74668. /**
  74669. * Gets the length in pixels of the blur sample region
  74670. */
  74671. get: function () {
  74672. return this._idealKernel;
  74673. },
  74674. /**
  74675. * Sets the length in pixels of the blur sample region
  74676. */
  74677. set: function (v) {
  74678. if (this._idealKernel === v) {
  74679. return;
  74680. }
  74681. v = Math.max(v, 1);
  74682. this._idealKernel = v;
  74683. this._kernel = this._nearestBestKernel(v);
  74684. if (!this.blockCompilation) {
  74685. this._updateParameters();
  74686. }
  74687. },
  74688. enumerable: true,
  74689. configurable: true
  74690. });
  74691. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  74692. /**
  74693. * Gets wether or not the blur is unpacking/repacking floats
  74694. */
  74695. get: function () {
  74696. return this._packedFloat;
  74697. },
  74698. /**
  74699. * Sets wether or not the blur needs to unpack/repack floats
  74700. */
  74701. set: function (v) {
  74702. if (this._packedFloat === v) {
  74703. return;
  74704. }
  74705. this._packedFloat = v;
  74706. if (!this.blockCompilation) {
  74707. this._updateParameters();
  74708. }
  74709. },
  74710. enumerable: true,
  74711. configurable: true
  74712. });
  74713. /**
  74714. * Updates the effect with the current post process compile time values and recompiles the shader.
  74715. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74716. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74717. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74718. * @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
  74719. * @param onCompiled Called when the shader has been compiled.
  74720. * @param onError Called if there is an error when compiling a shader.
  74721. */
  74722. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74723. if (defines === void 0) { defines = null; }
  74724. if (uniforms === void 0) { uniforms = null; }
  74725. if (samplers === void 0) { samplers = null; }
  74726. this._updateParameters(onCompiled, onError);
  74727. };
  74728. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  74729. // Generate sampling offsets and weights
  74730. var N = this._kernel;
  74731. var centerIndex = (N - 1) / 2;
  74732. // Generate Gaussian sampling weights over kernel
  74733. var offsets = [];
  74734. var weights = [];
  74735. var totalWeight = 0;
  74736. for (var i = 0; i < N; i++) {
  74737. var u = i / (N - 1);
  74738. var w = this._gaussianWeight(u * 2.0 - 1);
  74739. offsets[i] = (i - centerIndex);
  74740. weights[i] = w;
  74741. totalWeight += w;
  74742. }
  74743. // Normalize weights
  74744. for (var i = 0; i < weights.length; i++) {
  74745. weights[i] /= totalWeight;
  74746. }
  74747. // Optimize: combine samples to take advantage of hardware linear sampling
  74748. // Walk from left to center, combining pairs (symmetrically)
  74749. var linearSamplingWeights = [];
  74750. var linearSamplingOffsets = [];
  74751. var linearSamplingMap = [];
  74752. for (var i = 0; i <= centerIndex; i += 2) {
  74753. var j = Math.min(i + 1, Math.floor(centerIndex));
  74754. var singleCenterSample = i === j;
  74755. if (singleCenterSample) {
  74756. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74757. }
  74758. else {
  74759. var sharedCell = j === centerIndex;
  74760. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  74761. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  74762. if (offsetLinear === 0) {
  74763. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74764. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  74765. }
  74766. else {
  74767. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  74768. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  74769. }
  74770. }
  74771. }
  74772. for (var i = 0; i < linearSamplingMap.length; i++) {
  74773. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  74774. linearSamplingWeights[i] = linearSamplingMap[i].w;
  74775. }
  74776. // Replace with optimized
  74777. offsets = linearSamplingOffsets;
  74778. weights = linearSamplingWeights;
  74779. // Generate shaders
  74780. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  74781. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  74782. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  74783. var defines = "";
  74784. defines += this._staticDefines;
  74785. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  74786. if (this._staticDefines.indexOf("DOF") != -1) {
  74787. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  74788. varyingCount--;
  74789. }
  74790. for (var i = 0; i < varyingCount; i++) {
  74791. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  74792. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  74793. }
  74794. var depCount = 0;
  74795. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  74796. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  74797. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  74798. depCount++;
  74799. }
  74800. if (this.packedFloat) {
  74801. defines += "#define PACKEDFLOAT 1";
  74802. }
  74803. this.blockCompilation = false;
  74804. _super.prototype.updateEffect.call(this, defines, null, null, {
  74805. varyingCount: varyingCount,
  74806. depCount: depCount
  74807. }, onCompiled, onError);
  74808. };
  74809. /**
  74810. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  74811. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  74812. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  74813. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  74814. * The gaps between physical kernels are compensated for in the weighting of the samples
  74815. * @param idealKernel Ideal blur kernel.
  74816. * @return Nearest best kernel.
  74817. */
  74818. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  74819. var v = Math.round(idealKernel);
  74820. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  74821. var k = _a[_i];
  74822. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  74823. return Math.max(k, 3);
  74824. }
  74825. }
  74826. return Math.max(v, 3);
  74827. };
  74828. /**
  74829. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  74830. * @param x The point on the Gaussian distribution to sample.
  74831. * @return the value of the Gaussian function at x.
  74832. */
  74833. BlurPostProcess.prototype._gaussianWeight = function (x) {
  74834. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  74835. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  74836. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  74837. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  74838. // truncated at around 1.3% of peak strength.
  74839. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  74840. var sigma = (1 / 3);
  74841. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  74842. var exponent = -((x * x) / (2.0 * sigma * sigma));
  74843. var weight = (1.0 / denominator) * Math.exp(exponent);
  74844. return weight;
  74845. };
  74846. /**
  74847. * Generates a string that can be used as a floating point number in GLSL.
  74848. * @param x Value to print.
  74849. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  74850. * @return GLSL float string.
  74851. */
  74852. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  74853. if (decimalFigures === void 0) { decimalFigures = 8; }
  74854. return x.toFixed(decimalFigures).replace(/0+$/, '');
  74855. };
  74856. return BlurPostProcess;
  74857. }(BABYLON.PostProcess));
  74858. BABYLON.BlurPostProcess = BlurPostProcess;
  74859. })(BABYLON || (BABYLON = {}));
  74860. //# sourceMappingURL=babylon.blurPostProcess.js.map
  74861. var BABYLON;
  74862. (function (BABYLON) {
  74863. /**
  74864. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  74865. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  74866. * based on samples that have a large difference in distance than the center pixel.
  74867. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74868. */
  74869. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  74870. __extends(DepthOfFieldBlurPostProcess, _super);
  74871. /**
  74872. * Creates a new instance CircleOfConfusionPostProcess
  74873. * @param name The name of the effect.
  74874. * @param scene The scene the effect belongs to.
  74875. * @param direction The direction the blur should be applied.
  74876. * @param kernel The size of the kernel used to blur.
  74877. * @param options The required width/height ratio to downsize to before computing the render pass.
  74878. * @param camera The camera to apply the render pass to.
  74879. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  74880. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  74881. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74882. * @param engine The engine which the post process will be applied. (default: current engine)
  74883. * @param reusable If the post process can be reused on the same frame. (default: false)
  74884. * @param textureType Type of textures used when performing the post process. (default: 0)
  74885. * @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)
  74886. */
  74887. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  74888. if (imageToBlur === void 0) { imageToBlur = null; }
  74889. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74890. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74891. if (blockCompilation === void 0) { blockCompilation = false; }
  74892. 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;
  74893. _this.direction = direction;
  74894. _this.onApplyObservable.add(function (effect) {
  74895. if (imageToBlur != null) {
  74896. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  74897. }
  74898. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74899. if (scene.activeCamera) {
  74900. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  74901. }
  74902. });
  74903. return _this;
  74904. }
  74905. return DepthOfFieldBlurPostProcess;
  74906. }(BABYLON.BlurPostProcess));
  74907. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  74908. })(BABYLON || (BABYLON = {}));
  74909. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  74910. var BABYLON;
  74911. (function (BABYLON) {
  74912. /**
  74913. * Options to be set when merging outputs from the default pipeline.
  74914. */
  74915. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  74916. function DepthOfFieldMergePostProcessOptions() {
  74917. }
  74918. return DepthOfFieldMergePostProcessOptions;
  74919. }());
  74920. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  74921. /**
  74922. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  74923. */
  74924. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  74925. __extends(DepthOfFieldMergePostProcess, _super);
  74926. /**
  74927. * Creates a new instance of DepthOfFieldMergePostProcess
  74928. * @param name The name of the effect.
  74929. * @param originalFromInput Post process which's input will be used for the merge.
  74930. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  74931. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  74932. * @param options The required width/height ratio to downsize to before computing the render pass.
  74933. * @param camera The camera to apply the render pass to.
  74934. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74935. * @param engine The engine which the post process will be applied. (default: current engine)
  74936. * @param reusable If the post process can be reused on the same frame. (default: false)
  74937. * @param textureType Type of textures used when performing the post process. (default: 0)
  74938. * @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)
  74939. */
  74940. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74941. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74942. if (blockCompilation === void 0) { blockCompilation = false; }
  74943. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  74944. _this.blurSteps = blurSteps;
  74945. _this.onApplyObservable.add(function (effect) {
  74946. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  74947. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74948. blurSteps.forEach(function (step, index) {
  74949. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  74950. });
  74951. });
  74952. if (!blockCompilation) {
  74953. _this.updateEffect();
  74954. }
  74955. return _this;
  74956. }
  74957. /**
  74958. * Updates the effect with the current post process compile time values and recompiles the shader.
  74959. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74960. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74961. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74962. * @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
  74963. * @param onCompiled Called when the shader has been compiled.
  74964. * @param onError Called if there is an error when compiling a shader.
  74965. */
  74966. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74967. if (defines === void 0) { defines = null; }
  74968. if (uniforms === void 0) { uniforms = null; }
  74969. if (samplers === void 0) { samplers = null; }
  74970. if (!defines) {
  74971. defines = "";
  74972. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  74973. }
  74974. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  74975. };
  74976. return DepthOfFieldMergePostProcess;
  74977. }(BABYLON.PostProcess));
  74978. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  74979. })(BABYLON || (BABYLON = {}));
  74980. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  74981. var BABYLON;
  74982. (function (BABYLON) {
  74983. /**
  74984. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  74985. */
  74986. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  74987. __extends(CircleOfConfusionPostProcess, _super);
  74988. /**
  74989. * Creates a new instance CircleOfConfusionPostProcess
  74990. * @param name The name of the effect.
  74991. * @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.
  74992. * @param options The required width/height ratio to downsize to before computing the render pass.
  74993. * @param camera The camera to apply the render pass to.
  74994. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74995. * @param engine The engine which the post process will be applied. (default: current engine)
  74996. * @param reusable If the post process can be reused on the same frame. (default: false)
  74997. * @param textureType Type of textures used when performing the post process. (default: 0)
  74998. * @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)
  74999. */
  75000. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75001. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75002. if (blockCompilation === void 0) { blockCompilation = false; }
  75003. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75004. /**
  75005. * 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.
  75006. */
  75007. _this.lensSize = 50;
  75008. /**
  75009. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75010. */
  75011. _this.fStop = 1.4;
  75012. /**
  75013. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75014. */
  75015. _this.focusDistance = 2000;
  75016. /**
  75017. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75018. */
  75019. _this.focalLength = 50;
  75020. _this._depthTexture = null;
  75021. _this._depthTexture = depthTexture;
  75022. _this.onApplyObservable.add(function (effect) {
  75023. if (!_this._depthTexture) {
  75024. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75025. return;
  75026. }
  75027. effect.setTexture("depthSampler", _this._depthTexture);
  75028. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75029. var aperture = _this.lensSize / _this.fStop;
  75030. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75031. effect.setFloat('focusDistance', _this.focusDistance);
  75032. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75033. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75034. });
  75035. return _this;
  75036. }
  75037. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75038. /**
  75039. * 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.
  75040. */
  75041. set: function (value) {
  75042. this._depthTexture = value;
  75043. },
  75044. enumerable: true,
  75045. configurable: true
  75046. });
  75047. return CircleOfConfusionPostProcess;
  75048. }(BABYLON.PostProcess));
  75049. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75050. })(BABYLON || (BABYLON = {}));
  75051. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75052. var BABYLON;
  75053. (function (BABYLON) {
  75054. /**
  75055. * Specifies the level of max blur that should be applied when using the depth of field effect
  75056. */
  75057. var DepthOfFieldEffectBlurLevel;
  75058. (function (DepthOfFieldEffectBlurLevel) {
  75059. /**
  75060. * Subtle blur
  75061. */
  75062. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75063. /**
  75064. * Medium blur
  75065. */
  75066. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75067. /**
  75068. * Large blur
  75069. */
  75070. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75071. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75072. ;
  75073. /**
  75074. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75075. */
  75076. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75077. __extends(DepthOfFieldEffect, _super);
  75078. /**
  75079. * Creates a new instance DepthOfFieldEffect
  75080. * @param scene The scene the effect belongs to.
  75081. * @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.
  75082. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75083. * @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)
  75084. */
  75085. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75086. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75087. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75088. if (blockCompilation === void 0) { blockCompilation = false; }
  75089. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75090. return _this._effects;
  75091. }, true) || this;
  75092. /**
  75093. * Internal post processes in depth of field effect
  75094. */
  75095. _this._effects = [];
  75096. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75097. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75098. // 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)
  75099. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75100. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75101. _this._depthOfFieldBlurY = [];
  75102. _this._depthOfFieldBlurX = [];
  75103. var blurCount = 1;
  75104. var kernelSize = 15;
  75105. switch (blurLevel) {
  75106. case DepthOfFieldEffectBlurLevel.High: {
  75107. blurCount = 3;
  75108. kernelSize = 51;
  75109. break;
  75110. }
  75111. case DepthOfFieldEffectBlurLevel.Medium: {
  75112. blurCount = 2;
  75113. kernelSize = 31;
  75114. break;
  75115. }
  75116. default: {
  75117. kernelSize = 15;
  75118. blurCount = 1;
  75119. break;
  75120. }
  75121. }
  75122. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75123. var ratio = 1.0;
  75124. for (var i = 0; i < blurCount; i++) {
  75125. 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);
  75126. blurY.autoClear = false;
  75127. ratio = 0.75 / Math.pow(2, i);
  75128. 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);
  75129. blurX.autoClear = false;
  75130. _this._depthOfFieldBlurY.push(blurY);
  75131. _this._depthOfFieldBlurX.push(blurX);
  75132. }
  75133. // Set all post processes on the effect.
  75134. _this._effects = [_this._circleOfConfusion];
  75135. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75136. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75137. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75138. }
  75139. // Merge blurred images with original image based on circleOfConfusion
  75140. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75141. _this._dofMerge.autoClear = false;
  75142. _this._effects.push(_this._dofMerge);
  75143. return _this;
  75144. }
  75145. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75146. get: function () {
  75147. return this._circleOfConfusion.focalLength;
  75148. },
  75149. /**
  75150. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75151. */
  75152. set: function (value) {
  75153. this._circleOfConfusion.focalLength = value;
  75154. },
  75155. enumerable: true,
  75156. configurable: true
  75157. });
  75158. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75159. get: function () {
  75160. return this._circleOfConfusion.fStop;
  75161. },
  75162. /**
  75163. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75164. */
  75165. set: function (value) {
  75166. this._circleOfConfusion.fStop = value;
  75167. },
  75168. enumerable: true,
  75169. configurable: true
  75170. });
  75171. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75172. get: function () {
  75173. return this._circleOfConfusion.focusDistance;
  75174. },
  75175. /**
  75176. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75177. */
  75178. set: function (value) {
  75179. this._circleOfConfusion.focusDistance = value;
  75180. },
  75181. enumerable: true,
  75182. configurable: true
  75183. });
  75184. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75185. get: function () {
  75186. return this._circleOfConfusion.lensSize;
  75187. },
  75188. /**
  75189. * 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.
  75190. */
  75191. set: function (value) {
  75192. this._circleOfConfusion.lensSize = value;
  75193. },
  75194. enumerable: true,
  75195. configurable: true
  75196. });
  75197. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75198. /**
  75199. * 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.
  75200. */
  75201. set: function (value) {
  75202. this._circleOfConfusion.depthTexture = value;
  75203. },
  75204. enumerable: true,
  75205. configurable: true
  75206. });
  75207. /**
  75208. * Disposes each of the internal effects for a given camera.
  75209. * @param camera The camera to dispose the effect on.
  75210. */
  75211. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75212. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75213. this._effects[effectIndex].dispose(camera);
  75214. }
  75215. };
  75216. /**
  75217. * Internal
  75218. */
  75219. DepthOfFieldEffect.prototype._updateEffects = function () {
  75220. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75221. this._effects[effectIndex].updateEffect();
  75222. }
  75223. };
  75224. /**
  75225. * Internal
  75226. * @returns if all the contained post processes are ready.
  75227. */
  75228. DepthOfFieldEffect.prototype._isReady = function () {
  75229. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75230. if (!this._effects[effectIndex].isReady()) {
  75231. return false;
  75232. }
  75233. }
  75234. return true;
  75235. };
  75236. return DepthOfFieldEffect;
  75237. }(BABYLON.PostProcessRenderEffect));
  75238. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75239. })(BABYLON || (BABYLON = {}));
  75240. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75241. var BABYLON;
  75242. (function (BABYLON) {
  75243. /**
  75244. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75245. */
  75246. var BloomMergePostProcess = /** @class */ (function (_super) {
  75247. __extends(BloomMergePostProcess, _super);
  75248. /**
  75249. * Creates a new instance of @see BloomMergePostProcess
  75250. * @param name The name of the effect.
  75251. * @param originalFromInput Post process which's input will be used for the merge.
  75252. * @param blurred Blurred highlights post process which's output will be used.
  75253. * @param weight Weight of the bloom to be added to the original input.
  75254. * @param options The required width/height ratio to downsize to before computing the render pass.
  75255. * @param camera The camera to apply the render pass to.
  75256. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75257. * @param engine The engine which the post process will be applied. (default: current engine)
  75258. * @param reusable If the post process can be reused on the same frame. (default: false)
  75259. * @param textureType Type of textures used when performing the post process. (default: 0)
  75260. * @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)
  75261. */
  75262. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75263. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75264. if (blockCompilation === void 0) { blockCompilation = false; }
  75265. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75266. _this.weight = weight;
  75267. _this.onApplyObservable.add(function (effect) {
  75268. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75269. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75270. effect.setFloat("bloomWeight", _this.weight);
  75271. });
  75272. if (!blockCompilation) {
  75273. _this.updateEffect();
  75274. }
  75275. return _this;
  75276. }
  75277. return BloomMergePostProcess;
  75278. }(BABYLON.PostProcess));
  75279. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75280. })(BABYLON || (BABYLON = {}));
  75281. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75282. var BABYLON;
  75283. (function (BABYLON) {
  75284. /**
  75285. * 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.
  75286. */
  75287. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75288. __extends(ExtractHighlightsPostProcess, _super);
  75289. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75290. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75291. if (blockCompilation === void 0) { blockCompilation = false; }
  75292. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75293. /**
  75294. * The luminance threshold, pixels below this value will be set to black.
  75295. */
  75296. _this.threshold = 0.9;
  75297. /**
  75298. * Internal
  75299. */
  75300. _this._exposure = 1;
  75301. /**
  75302. * Post process which has the input texture to be used when performing highlight extraction
  75303. */
  75304. _this._inputPostProcess = null;
  75305. _this.onApplyObservable.add(function (effect) {
  75306. if (_this._inputPostProcess) {
  75307. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75308. }
  75309. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75310. effect.setFloat('exposure', _this._exposure);
  75311. });
  75312. return _this;
  75313. }
  75314. return ExtractHighlightsPostProcess;
  75315. }(BABYLON.PostProcess));
  75316. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75317. })(BABYLON || (BABYLON = {}));
  75318. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75319. var BABYLON;
  75320. (function (BABYLON) {
  75321. /**
  75322. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75323. */
  75324. var BloomEffect = /** @class */ (function (_super) {
  75325. __extends(BloomEffect, _super);
  75326. /**
  75327. * Creates a new instance of @see BloomEffect
  75328. * @param scene The scene the effect belongs to.
  75329. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75330. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75331. * @param bloomWeight The the strength of bloom.
  75332. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75333. * @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)
  75334. */
  75335. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75336. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75337. if (blockCompilation === void 0) { blockCompilation = false; }
  75338. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75339. return _this._effects;
  75340. }, true) || this;
  75341. _this.bloomScale = bloomScale;
  75342. /**
  75343. * Internal
  75344. */
  75345. _this._effects = [];
  75346. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75347. _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);
  75348. _this._blurX.alwaysForcePOT = true;
  75349. _this._blurX.autoClear = false;
  75350. _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);
  75351. _this._blurY.alwaysForcePOT = true;
  75352. _this._blurY.autoClear = false;
  75353. _this.kernel = bloomKernel;
  75354. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75355. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75356. _this._merge.autoClear = false;
  75357. _this._effects.push(_this._merge);
  75358. return _this;
  75359. }
  75360. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75361. /**
  75362. * The luminance threshold to find bright areas of the image to bloom.
  75363. */
  75364. get: function () {
  75365. return this._downscale.threshold;
  75366. },
  75367. set: function (value) {
  75368. this._downscale.threshold = value;
  75369. },
  75370. enumerable: true,
  75371. configurable: true
  75372. });
  75373. Object.defineProperty(BloomEffect.prototype, "weight", {
  75374. /**
  75375. * The strength of the bloom.
  75376. */
  75377. get: function () {
  75378. return this._merge.weight;
  75379. },
  75380. set: function (value) {
  75381. this._merge.weight = value;
  75382. },
  75383. enumerable: true,
  75384. configurable: true
  75385. });
  75386. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75387. /**
  75388. * Specifies the size of the bloom blur kernel, relative to the final output size
  75389. */
  75390. get: function () {
  75391. return this._blurX.kernel / this.bloomScale;
  75392. },
  75393. set: function (value) {
  75394. this._blurX.kernel = value * this.bloomScale;
  75395. this._blurY.kernel = value * this.bloomScale;
  75396. },
  75397. enumerable: true,
  75398. configurable: true
  75399. });
  75400. /**
  75401. * Disposes each of the internal effects for a given camera.
  75402. * @param camera The camera to dispose the effect on.
  75403. */
  75404. BloomEffect.prototype.disposeEffects = function (camera) {
  75405. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75406. this._effects[effectIndex].dispose(camera);
  75407. }
  75408. };
  75409. /**
  75410. * Internal
  75411. */
  75412. BloomEffect.prototype._updateEffects = function () {
  75413. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75414. this._effects[effectIndex].updateEffect();
  75415. }
  75416. };
  75417. /**
  75418. * Internal
  75419. * @returns if all the contained post processes are ready.
  75420. */
  75421. BloomEffect.prototype._isReady = function () {
  75422. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75423. if (!this._effects[effectIndex].isReady()) {
  75424. return false;
  75425. }
  75426. }
  75427. return true;
  75428. };
  75429. return BloomEffect;
  75430. }(BABYLON.PostProcessRenderEffect));
  75431. BABYLON.BloomEffect = BloomEffect;
  75432. })(BABYLON || (BABYLON = {}));
  75433. //# sourceMappingURL=babylon.bloomEffect.js.map
  75434. var BABYLON;
  75435. (function (BABYLON) {
  75436. /**
  75437. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  75438. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  75439. */
  75440. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  75441. __extends(DefaultRenderingPipeline, _super);
  75442. /**
  75443. * @constructor
  75444. * @param {string} name - The rendering pipeline name (default: "")
  75445. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  75446. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  75447. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  75448. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  75449. */
  75450. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  75451. if (name === void 0) { name = ""; }
  75452. if (hdr === void 0) { hdr = true; }
  75453. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75454. if (automaticBuild === void 0) { automaticBuild = true; }
  75455. var _this = _super.call(this, scene.getEngine(), name) || this;
  75456. _this._originalCameras = [];
  75457. /**
  75458. * ID of the sharpen post process,
  75459. */
  75460. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  75461. /**
  75462. * ID of the image processing post process;
  75463. */
  75464. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  75465. /**
  75466. * ID of the Fast Approximate Anti-Aliasing post process;
  75467. */
  75468. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  75469. /**
  75470. * ID of the chromatic aberration post process,
  75471. */
  75472. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  75473. /**
  75474. * ID of the grain post process
  75475. */
  75476. _this.GrainPostProcessId = "GrainPostProcessEffect";
  75477. /**
  75478. * Glow post process which adds a glow to emmisive areas of the image
  75479. */
  75480. _this._glowLayer = null;
  75481. /**
  75482. * Animations which can be used to tweak settings over a period of time
  75483. */
  75484. _this.animations = [];
  75485. _this._imageProcessingConfigurationObserver = null;
  75486. // Values
  75487. _this._sharpenEnabled = false;
  75488. _this._bloomEnabled = false;
  75489. _this._depthOfFieldEnabled = false;
  75490. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  75491. _this._fxaaEnabled = false;
  75492. _this._imageProcessingEnabled = true;
  75493. _this._bloomScale = 0.5;
  75494. _this._chromaticAberrationEnabled = false;
  75495. _this._grainEnabled = false;
  75496. _this._buildAllowed = true;
  75497. _this._resizeObserver = null;
  75498. _this._hardwareScaleLevel = 1.0;
  75499. _this._bloomKernel = 64;
  75500. /**
  75501. * Specifies the weight of the bloom in the final rendering
  75502. */
  75503. _this._bloomWeight = 0.15;
  75504. /**
  75505. * Specifies the luma threshold for the area that will be blurred by the bloom
  75506. */
  75507. _this._bloomThreshold = 0.9;
  75508. _this._samples = 1;
  75509. _this._hasCleared = false;
  75510. _this._prevPostProcess = null;
  75511. _this._prevPrevPostProcess = null;
  75512. _this._cameras = cameras || scene.cameras;
  75513. _this._originalCameras = _this._cameras.slice();
  75514. _this._buildAllowed = automaticBuild;
  75515. // Initialize
  75516. _this._scene = scene;
  75517. var caps = _this._scene.getEngine().getCaps();
  75518. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  75519. // Misc
  75520. if (_this._hdr) {
  75521. if (caps.textureHalfFloatRender) {
  75522. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75523. }
  75524. else if (caps.textureFloatRender) {
  75525. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75526. }
  75527. }
  75528. else {
  75529. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75530. }
  75531. // Attach
  75532. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75533. var engine = _this._scene.getEngine();
  75534. // Create post processes before hand so they can be modified before enabled.
  75535. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  75536. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75537. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  75538. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  75539. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  75540. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75541. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  75542. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75543. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  75544. _this._resizeObserver = engine.onResizeObservable.add(function () {
  75545. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  75546. _this.bloomKernel = _this.bloomKernel;
  75547. });
  75548. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  75549. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  75550. });
  75551. _this._buildPipeline();
  75552. return _this;
  75553. }
  75554. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  75555. get: function () {
  75556. return this._sharpenEnabled;
  75557. },
  75558. /**
  75559. * Enable or disable the sharpen process from the pipeline
  75560. */
  75561. set: function (enabled) {
  75562. if (this._sharpenEnabled === enabled) {
  75563. return;
  75564. }
  75565. this._sharpenEnabled = enabled;
  75566. this._buildPipeline();
  75567. },
  75568. enumerable: true,
  75569. configurable: true
  75570. });
  75571. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  75572. /**
  75573. * Specifies the size of the bloom blur kernel, relative to the final output size
  75574. */
  75575. get: function () {
  75576. return this._bloomKernel;
  75577. },
  75578. set: function (value) {
  75579. this._bloomKernel = value;
  75580. this.bloom.kernel = value / this._hardwareScaleLevel;
  75581. },
  75582. enumerable: true,
  75583. configurable: true
  75584. });
  75585. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  75586. get: function () {
  75587. return this._bloomWeight;
  75588. },
  75589. /**
  75590. * The strength of the bloom.
  75591. */
  75592. set: function (value) {
  75593. if (this._bloomWeight === value) {
  75594. return;
  75595. }
  75596. this.bloom.weight = value;
  75597. this._bloomWeight = value;
  75598. },
  75599. enumerable: true,
  75600. configurable: true
  75601. });
  75602. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  75603. get: function () {
  75604. return this._bloomThreshold;
  75605. },
  75606. /**
  75607. * The strength of the bloom.
  75608. */
  75609. set: function (value) {
  75610. if (this._bloomThreshold === value) {
  75611. return;
  75612. }
  75613. this.bloom.threshold = value;
  75614. this._bloomThreshold = value;
  75615. },
  75616. enumerable: true,
  75617. configurable: true
  75618. });
  75619. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  75620. get: function () {
  75621. return this._bloomScale;
  75622. },
  75623. /**
  75624. * The scale of the bloom, lower value will provide better performance.
  75625. */
  75626. set: function (value) {
  75627. if (this._bloomScale === value) {
  75628. return;
  75629. }
  75630. this._bloomScale = value;
  75631. // recreate bloom and dispose old as this setting is not dynamic
  75632. this._rebuildBloom();
  75633. this._buildPipeline();
  75634. },
  75635. enumerable: true,
  75636. configurable: true
  75637. });
  75638. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  75639. get: function () {
  75640. return this._bloomEnabled;
  75641. },
  75642. /**
  75643. * Enable or disable the bloom from the pipeline
  75644. */
  75645. set: function (enabled) {
  75646. if (this._bloomEnabled === enabled) {
  75647. return;
  75648. }
  75649. this._bloomEnabled = enabled;
  75650. this._buildPipeline();
  75651. },
  75652. enumerable: true,
  75653. configurable: true
  75654. });
  75655. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  75656. // recreate bloom and dispose old as this setting is not dynamic
  75657. var oldBloom = this.bloom;
  75658. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  75659. this.bloom.threshold = oldBloom.threshold;
  75660. for (var i = 0; i < this._cameras.length; i++) {
  75661. oldBloom.disposeEffects(this._cameras[i]);
  75662. }
  75663. };
  75664. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  75665. /**
  75666. * If the depth of field is enabled.
  75667. */
  75668. get: function () {
  75669. return this._depthOfFieldEnabled;
  75670. },
  75671. set: function (enabled) {
  75672. if (this._depthOfFieldEnabled === enabled) {
  75673. return;
  75674. }
  75675. this._depthOfFieldEnabled = enabled;
  75676. this._buildPipeline();
  75677. },
  75678. enumerable: true,
  75679. configurable: true
  75680. });
  75681. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  75682. /**
  75683. * Blur level of the depth of field effect. (Higher blur will effect performance)
  75684. */
  75685. get: function () {
  75686. return this._depthOfFieldBlurLevel;
  75687. },
  75688. set: function (value) {
  75689. if (this._depthOfFieldBlurLevel === value) {
  75690. return;
  75691. }
  75692. this._depthOfFieldBlurLevel = value;
  75693. // recreate dof and dispose old as this setting is not dynamic
  75694. var oldDof = this.depthOfField;
  75695. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  75696. this.depthOfField.focalLength = oldDof.focalLength;
  75697. this.depthOfField.focusDistance = oldDof.focusDistance;
  75698. this.depthOfField.fStop = oldDof.fStop;
  75699. this.depthOfField.lensSize = oldDof.lensSize;
  75700. for (var i = 0; i < this._cameras.length; i++) {
  75701. oldDof.disposeEffects(this._cameras[i]);
  75702. }
  75703. this._buildPipeline();
  75704. },
  75705. enumerable: true,
  75706. configurable: true
  75707. });
  75708. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  75709. get: function () {
  75710. return this._fxaaEnabled;
  75711. },
  75712. /**
  75713. * If the anti aliasing is enabled.
  75714. */
  75715. set: function (enabled) {
  75716. if (this._fxaaEnabled === enabled) {
  75717. return;
  75718. }
  75719. this._fxaaEnabled = enabled;
  75720. this._buildPipeline();
  75721. },
  75722. enumerable: true,
  75723. configurable: true
  75724. });
  75725. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  75726. get: function () {
  75727. return this._samples;
  75728. },
  75729. /**
  75730. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  75731. */
  75732. set: function (sampleCount) {
  75733. if (this._samples === sampleCount) {
  75734. return;
  75735. }
  75736. this._samples = sampleCount;
  75737. this._buildPipeline();
  75738. },
  75739. enumerable: true,
  75740. configurable: true
  75741. });
  75742. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  75743. get: function () {
  75744. return this._imageProcessingEnabled;
  75745. },
  75746. /**
  75747. * If image processing is enabled.
  75748. */
  75749. set: function (enabled) {
  75750. if (this._imageProcessingEnabled === enabled) {
  75751. return;
  75752. }
  75753. this._imageProcessingEnabled = enabled;
  75754. this._buildPipeline();
  75755. },
  75756. enumerable: true,
  75757. configurable: true
  75758. });
  75759. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  75760. get: function () {
  75761. return this._glowLayer == null;
  75762. },
  75763. /**
  75764. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  75765. */
  75766. set: function (enabled) {
  75767. if (enabled && !this._glowLayer) {
  75768. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  75769. }
  75770. else if (!enabled && this._glowLayer) {
  75771. this._glowLayer.dispose();
  75772. this._glowLayer = null;
  75773. }
  75774. },
  75775. enumerable: true,
  75776. configurable: true
  75777. });
  75778. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  75779. get: function () {
  75780. return this._chromaticAberrationEnabled;
  75781. },
  75782. /**
  75783. * Enable or disable the chromaticAberration process from the pipeline
  75784. */
  75785. set: function (enabled) {
  75786. if (this._chromaticAberrationEnabled === enabled) {
  75787. return;
  75788. }
  75789. this._chromaticAberrationEnabled = enabled;
  75790. this._buildPipeline();
  75791. },
  75792. enumerable: true,
  75793. configurable: true
  75794. });
  75795. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  75796. get: function () {
  75797. return this._grainEnabled;
  75798. },
  75799. /**
  75800. * Enable or disable the grain process from the pipeline
  75801. */
  75802. set: function (enabled) {
  75803. if (this._grainEnabled === enabled) {
  75804. return;
  75805. }
  75806. this._grainEnabled = enabled;
  75807. this._buildPipeline();
  75808. },
  75809. enumerable: true,
  75810. configurable: true
  75811. });
  75812. /**
  75813. * Force the compilation of the entire pipeline.
  75814. */
  75815. DefaultRenderingPipeline.prototype.prepare = function () {
  75816. var previousState = this._buildAllowed;
  75817. this._buildAllowed = true;
  75818. this._buildPipeline();
  75819. this._buildAllowed = previousState;
  75820. };
  75821. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  75822. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  75823. if (this._hasCleared) {
  75824. postProcess.autoClear = false;
  75825. }
  75826. else {
  75827. postProcess.autoClear = true;
  75828. this._scene.autoClear = false;
  75829. this._hasCleared = true;
  75830. }
  75831. if (!skipTextureSharing) {
  75832. if (this._prevPrevPostProcess) {
  75833. postProcess.shareOutputWith(this._prevPrevPostProcess);
  75834. }
  75835. else {
  75836. postProcess.useOwnOutput();
  75837. }
  75838. if (this._prevPostProcess) {
  75839. this._prevPrevPostProcess = this._prevPostProcess;
  75840. }
  75841. this._prevPostProcess = postProcess;
  75842. }
  75843. };
  75844. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  75845. var _this = this;
  75846. if (!this._buildAllowed) {
  75847. return;
  75848. }
  75849. this._scene.autoClear = true;
  75850. var engine = this._scene.getEngine();
  75851. this._disposePostProcesses();
  75852. if (this._cameras !== null) {
  75853. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75854. // get back cameras to be used to reattach pipeline
  75855. this._cameras = this._originalCameras.slice();
  75856. }
  75857. this._reset();
  75858. this._prevPostProcess = null;
  75859. this._prevPrevPostProcess = null;
  75860. this._hasCleared = false;
  75861. if (this.depthOfFieldEnabled) {
  75862. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  75863. this.depthOfField.depthTexture = depthTexture;
  75864. if (!this.depthOfField._isReady()) {
  75865. this.depthOfField._updateEffects();
  75866. }
  75867. this.addEffect(this.depthOfField);
  75868. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  75869. }
  75870. if (this.bloomEnabled) {
  75871. if (!this.bloom._isReady()) {
  75872. this.bloom._updateEffects();
  75873. }
  75874. this.addEffect(this.bloom);
  75875. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  75876. }
  75877. if (this._imageProcessingEnabled) {
  75878. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75879. if (this._hdr) {
  75880. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  75881. this._setAutoClearAndTextureSharing(this.imageProcessing);
  75882. }
  75883. else {
  75884. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  75885. }
  75886. }
  75887. if (this.sharpenEnabled) {
  75888. if (!this.sharpen.isReady()) {
  75889. this.sharpen.updateEffect();
  75890. }
  75891. this.addEffect(this._sharpenEffect);
  75892. this._setAutoClearAndTextureSharing(this.sharpen);
  75893. }
  75894. if (this.grainEnabled) {
  75895. if (!this.grain.isReady()) {
  75896. this.grain.updateEffect();
  75897. }
  75898. this.addEffect(this._grainEffect);
  75899. this._setAutoClearAndTextureSharing(this.grain);
  75900. }
  75901. if (this.chromaticAberrationEnabled) {
  75902. if (!this.chromaticAberration.isReady()) {
  75903. this.chromaticAberration.updateEffect();
  75904. }
  75905. this.addEffect(this._chromaticAberrationEffect);
  75906. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  75907. }
  75908. if (this.fxaaEnabled) {
  75909. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75910. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  75911. this._setAutoClearAndTextureSharing(this.fxaa, true);
  75912. }
  75913. if (this._cameras !== null) {
  75914. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  75915. }
  75916. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  75917. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  75918. }
  75919. };
  75920. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  75921. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  75922. for (var i = 0; i < this._cameras.length; i++) {
  75923. var camera = this._cameras[i];
  75924. if (this.imageProcessing) {
  75925. this.imageProcessing.dispose(camera);
  75926. }
  75927. if (this.fxaa) {
  75928. this.fxaa.dispose(camera);
  75929. }
  75930. // These are created in the constructor and should not be disposed on every pipeline change
  75931. if (disposeNonRecreated) {
  75932. if (this.sharpen) {
  75933. this.sharpen.dispose(camera);
  75934. }
  75935. if (this.depthOfField) {
  75936. this.depthOfField.disposeEffects(camera);
  75937. }
  75938. if (this.bloom) {
  75939. this.bloom.disposeEffects(camera);
  75940. }
  75941. if (this.chromaticAberration) {
  75942. this.chromaticAberration.dispose(camera);
  75943. }
  75944. if (this.grain) {
  75945. this.grain.dispose(camera);
  75946. }
  75947. if (this._glowLayer) {
  75948. this._glowLayer.dispose();
  75949. }
  75950. }
  75951. }
  75952. this.imageProcessing = null;
  75953. this.fxaa = null;
  75954. if (disposeNonRecreated) {
  75955. this.sharpen = null;
  75956. this._sharpenEffect = null;
  75957. this.depthOfField = null;
  75958. this.bloom = null;
  75959. this.chromaticAberration = null;
  75960. this._chromaticAberrationEffect = null;
  75961. this.grain = null;
  75962. this._grainEffect = null;
  75963. this._glowLayer = null;
  75964. }
  75965. };
  75966. /**
  75967. * Dispose of the pipeline and stop all post processes
  75968. */
  75969. DefaultRenderingPipeline.prototype.dispose = function () {
  75970. this._disposePostProcesses(true);
  75971. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75972. this._scene.autoClear = true;
  75973. if (this._resizeObserver) {
  75974. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  75975. this._resizeObserver = null;
  75976. }
  75977. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  75978. _super.prototype.dispose.call(this);
  75979. };
  75980. /**
  75981. * Serialize the rendering pipeline (Used when exporting)
  75982. * @returns the serialized object
  75983. */
  75984. DefaultRenderingPipeline.prototype.serialize = function () {
  75985. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75986. serializationObject.customType = "DefaultRenderingPipeline";
  75987. return serializationObject;
  75988. };
  75989. /**
  75990. * Parse the serialized pipeline
  75991. * @param source Source pipeline.
  75992. * @param scene The scene to load the pipeline to.
  75993. * @param rootUrl The URL of the serialized pipeline.
  75994. * @returns An instantiated pipeline from the serialized object.
  75995. */
  75996. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75997. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  75998. };
  75999. __decorate([
  76000. BABYLON.serialize()
  76001. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76002. __decorate([
  76003. BABYLON.serialize()
  76004. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76005. __decorate([
  76006. BABYLON.serialize()
  76007. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76008. __decorate([
  76009. BABYLON.serialize()
  76010. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76011. __decorate([
  76012. BABYLON.serialize()
  76013. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76014. __decorate([
  76015. BABYLON.serialize()
  76016. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76017. __decorate([
  76018. BABYLON.serialize()
  76019. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76020. __decorate([
  76021. BABYLON.serialize()
  76022. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76023. __decorate([
  76024. BABYLON.serialize()
  76025. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76026. __decorate([
  76027. BABYLON.serialize()
  76028. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76029. __decorate([
  76030. BABYLON.serialize()
  76031. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76032. __decorate([
  76033. BABYLON.serialize()
  76034. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76035. __decorate([
  76036. BABYLON.serialize()
  76037. ], DefaultRenderingPipeline.prototype, "samples", null);
  76038. __decorate([
  76039. BABYLON.serialize()
  76040. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76041. __decorate([
  76042. BABYLON.serialize()
  76043. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76044. __decorate([
  76045. BABYLON.serialize()
  76046. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76047. __decorate([
  76048. BABYLON.serialize()
  76049. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76050. return DefaultRenderingPipeline;
  76051. }(BABYLON.PostProcessRenderPipeline));
  76052. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76053. })(BABYLON || (BABYLON = {}));
  76054. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76055. var BABYLON;
  76056. (function (BABYLON) {
  76057. /**
  76058. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76059. */
  76060. var GeometryBufferRenderer = /** @class */ (function () {
  76061. /**
  76062. * Creates a new G Buffer for the scene
  76063. * @param scene The scene the buffer belongs to
  76064. * @param ratio How big is the buffer related to the main canvas.
  76065. */
  76066. function GeometryBufferRenderer(scene, ratio) {
  76067. if (ratio === void 0) { ratio = 1; }
  76068. this._enablePosition = false;
  76069. this._scene = scene;
  76070. this._ratio = ratio;
  76071. // Render target
  76072. this._createRenderTargets();
  76073. }
  76074. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76075. /**
  76076. * Set the render list (meshes to be rendered) used in the G buffer.
  76077. */
  76078. set: function (meshes) {
  76079. this._multiRenderTarget.renderList = meshes;
  76080. },
  76081. enumerable: true,
  76082. configurable: true
  76083. });
  76084. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76085. /**
  76086. * Gets wether or not G buffer are supported by the running hardware.
  76087. * This requires draw buffer supports
  76088. */
  76089. get: function () {
  76090. return this._multiRenderTarget.isSupported;
  76091. },
  76092. enumerable: true,
  76093. configurable: true
  76094. });
  76095. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76096. /**
  76097. * Gets wether or not position are enabled for the G buffer.
  76098. */
  76099. get: function () {
  76100. return this._enablePosition;
  76101. },
  76102. /**
  76103. * Sets wether or not position are enabled for the G buffer.
  76104. */
  76105. set: function (enable) {
  76106. this._enablePosition = enable;
  76107. this.dispose();
  76108. this._createRenderTargets();
  76109. },
  76110. enumerable: true,
  76111. configurable: true
  76112. });
  76113. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76114. /**
  76115. * Gets the scene associated with the buffer.
  76116. */
  76117. get: function () {
  76118. return this._scene;
  76119. },
  76120. enumerable: true,
  76121. configurable: true
  76122. });
  76123. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76124. /**
  76125. * Gets the ratio used by the buffer during its creation.
  76126. * How big is the buffer related to the main canvas.
  76127. */
  76128. get: function () {
  76129. return this._ratio;
  76130. },
  76131. enumerable: true,
  76132. configurable: true
  76133. });
  76134. /**
  76135. * Checks wether everything is ready to render a submesh to the G buffer.
  76136. * @param subMesh the submesh to check readiness for
  76137. * @param useInstances is the mesh drawn using instance or not
  76138. * @returns true if ready otherwise false
  76139. */
  76140. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76141. var material = subMesh.getMaterial();
  76142. if (material && material.disableDepthWrite) {
  76143. return false;
  76144. }
  76145. var defines = [];
  76146. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76147. var mesh = subMesh.getMesh();
  76148. // Alpha test
  76149. if (material && material.needAlphaTesting()) {
  76150. defines.push("#define ALPHATEST");
  76151. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76152. attribs.push(BABYLON.VertexBuffer.UVKind);
  76153. defines.push("#define UV1");
  76154. }
  76155. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76156. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76157. defines.push("#define UV2");
  76158. }
  76159. }
  76160. // Buffers
  76161. if (this._enablePosition) {
  76162. defines.push("#define POSITION");
  76163. }
  76164. // Bones
  76165. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76166. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76167. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76168. if (mesh.numBoneInfluencers > 4) {
  76169. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76170. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76171. }
  76172. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76173. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76174. }
  76175. else {
  76176. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76177. }
  76178. // Instances
  76179. if (useInstances) {
  76180. defines.push("#define INSTANCES");
  76181. attribs.push("world0");
  76182. attribs.push("world1");
  76183. attribs.push("world2");
  76184. attribs.push("world3");
  76185. }
  76186. // Get correct effect
  76187. var join = defines.join("\n");
  76188. if (this._cachedDefines !== join) {
  76189. this._cachedDefines = join;
  76190. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76191. }
  76192. return this._effect.isReady();
  76193. };
  76194. /**
  76195. * Gets the current underlying G Buffer.
  76196. * @returns the buffer
  76197. */
  76198. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76199. return this._multiRenderTarget;
  76200. };
  76201. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76202. /**
  76203. * Gets the number of samples used to render the buffer (anti aliasing).
  76204. */
  76205. get: function () {
  76206. return this._multiRenderTarget.samples;
  76207. },
  76208. /**
  76209. * Sets the number of samples used to render the buffer (anti aliasing).
  76210. */
  76211. set: function (value) {
  76212. this._multiRenderTarget.samples = value;
  76213. },
  76214. enumerable: true,
  76215. configurable: true
  76216. });
  76217. /**
  76218. * Disposes the renderer and frees up associated resources.
  76219. */
  76220. GeometryBufferRenderer.prototype.dispose = function () {
  76221. this.getGBuffer().dispose();
  76222. };
  76223. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76224. var _this = this;
  76225. var engine = this._scene.getEngine();
  76226. var count = this._enablePosition ? 3 : 2;
  76227. 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 });
  76228. if (!this.isSupported) {
  76229. return;
  76230. }
  76231. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76232. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76233. this._multiRenderTarget.refreshRate = 1;
  76234. this._multiRenderTarget.renderParticles = false;
  76235. this._multiRenderTarget.renderList = null;
  76236. // set default depth value to 1.0 (far away)
  76237. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76238. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76239. });
  76240. // Custom render function
  76241. var renderSubMesh = function (subMesh) {
  76242. var mesh = subMesh.getRenderingMesh();
  76243. var scene = _this._scene;
  76244. var engine = scene.getEngine();
  76245. var material = subMesh.getMaterial();
  76246. if (!material) {
  76247. return;
  76248. }
  76249. // Culling
  76250. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76251. // Managing instances
  76252. var batch = mesh._getInstancesRenderList(subMesh._id);
  76253. if (batch.mustReturn) {
  76254. return;
  76255. }
  76256. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76257. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76258. engine.enableEffect(_this._effect);
  76259. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76260. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76261. _this._effect.setMatrix("view", scene.getViewMatrix());
  76262. // Alpha test
  76263. if (material && material.needAlphaTesting()) {
  76264. var alphaTexture = material.getAlphaTestTexture();
  76265. if (alphaTexture) {
  76266. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76267. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76268. }
  76269. }
  76270. // Bones
  76271. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76272. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76273. }
  76274. // Draw
  76275. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76276. }
  76277. };
  76278. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76279. var index;
  76280. if (depthOnlySubMeshes.length) {
  76281. engine.setColorWrite(false);
  76282. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76283. renderSubMesh(depthOnlySubMeshes.data[index]);
  76284. }
  76285. engine.setColorWrite(true);
  76286. }
  76287. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76288. renderSubMesh(opaqueSubMeshes.data[index]);
  76289. }
  76290. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76291. renderSubMesh(alphaTestSubMeshes.data[index]);
  76292. }
  76293. };
  76294. };
  76295. return GeometryBufferRenderer;
  76296. }());
  76297. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76298. })(BABYLON || (BABYLON = {}));
  76299. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76300. var BABYLON;
  76301. (function (BABYLON) {
  76302. /**
  76303. * This groups together the common properties used for image processing either in direct forward pass
  76304. * or through post processing effect depending on the use of the image processing pipeline in your scene
  76305. * or not.
  76306. */
  76307. var ImageProcessingConfiguration = /** @class */ (function () {
  76308. function ImageProcessingConfiguration() {
  76309. /**
  76310. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  76311. */
  76312. this.colorCurves = new BABYLON.ColorCurves();
  76313. this._colorCurvesEnabled = false;
  76314. this._colorGradingEnabled = false;
  76315. this._colorGradingWithGreenDepth = true;
  76316. this._colorGradingBGR = true;
  76317. this._exposure = 1.0;
  76318. this._toneMappingEnabled = false;
  76319. this._contrast = 1.0;
  76320. /**
  76321. * Vignette stretch size.
  76322. */
  76323. this.vignetteStretch = 0;
  76324. /**
  76325. * Vignette centre X Offset.
  76326. */
  76327. this.vignetteCentreX = 0;
  76328. /**
  76329. * Vignette centre Y Offset.
  76330. */
  76331. this.vignetteCentreY = 0;
  76332. /**
  76333. * Vignette weight or intensity of the vignette effect.
  76334. */
  76335. this.vignetteWeight = 1.5;
  76336. /**
  76337. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  76338. * if vignetteEnabled is set to true.
  76339. */
  76340. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  76341. /**
  76342. * Camera field of view used by the Vignette effect.
  76343. */
  76344. this.vignetteCameraFov = 0.5;
  76345. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  76346. this._vignetteEnabled = false;
  76347. this._applyByPostProcess = false;
  76348. this._isEnabled = true;
  76349. /**
  76350. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  76351. */
  76352. this.onUpdateParameters = new BABYLON.Observable();
  76353. }
  76354. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  76355. /**
  76356. * Gets wether the color curves effect is enabled.
  76357. */
  76358. get: function () {
  76359. return this._colorCurvesEnabled;
  76360. },
  76361. /**
  76362. * Sets wether the color curves effect is enabled.
  76363. */
  76364. set: function (value) {
  76365. if (this._colorCurvesEnabled === value) {
  76366. return;
  76367. }
  76368. this._colorCurvesEnabled = value;
  76369. this._updateParameters();
  76370. },
  76371. enumerable: true,
  76372. configurable: true
  76373. });
  76374. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  76375. /**
  76376. * Gets wether the color grading effect is enabled.
  76377. */
  76378. get: function () {
  76379. return this._colorGradingEnabled;
  76380. },
  76381. /**
  76382. * Sets wether the color grading effect is enabled.
  76383. */
  76384. set: function (value) {
  76385. if (this._colorGradingEnabled === value) {
  76386. return;
  76387. }
  76388. this._colorGradingEnabled = value;
  76389. this._updateParameters();
  76390. },
  76391. enumerable: true,
  76392. configurable: true
  76393. });
  76394. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  76395. /**
  76396. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  76397. */
  76398. get: function () {
  76399. return this._colorGradingWithGreenDepth;
  76400. },
  76401. /**
  76402. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  76403. */
  76404. set: function (value) {
  76405. if (this._colorGradingWithGreenDepth === value) {
  76406. return;
  76407. }
  76408. this._colorGradingWithGreenDepth = value;
  76409. this._updateParameters();
  76410. },
  76411. enumerable: true,
  76412. configurable: true
  76413. });
  76414. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  76415. /**
  76416. * Gets wether the color grading texture contains BGR values.
  76417. */
  76418. get: function () {
  76419. return this._colorGradingBGR;
  76420. },
  76421. /**
  76422. * Sets wether the color grading texture contains BGR values.
  76423. */
  76424. set: function (value) {
  76425. if (this._colorGradingBGR === value) {
  76426. return;
  76427. }
  76428. this._colorGradingBGR = value;
  76429. this._updateParameters();
  76430. },
  76431. enumerable: true,
  76432. configurable: true
  76433. });
  76434. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  76435. /**
  76436. * Gets the Exposure used in the effect.
  76437. */
  76438. get: function () {
  76439. return this._exposure;
  76440. },
  76441. /**
  76442. * Sets the Exposure used in the effect.
  76443. */
  76444. set: function (value) {
  76445. if (this._exposure === value) {
  76446. return;
  76447. }
  76448. this._exposure = value;
  76449. this._updateParameters();
  76450. },
  76451. enumerable: true,
  76452. configurable: true
  76453. });
  76454. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  76455. /**
  76456. * Gets wether the tone mapping effect is enabled.
  76457. */
  76458. get: function () {
  76459. return this._toneMappingEnabled;
  76460. },
  76461. /**
  76462. * Sets wether the tone mapping effect is enabled.
  76463. */
  76464. set: function (value) {
  76465. if (this._toneMappingEnabled === value) {
  76466. return;
  76467. }
  76468. this._toneMappingEnabled = value;
  76469. this._updateParameters();
  76470. },
  76471. enumerable: true,
  76472. configurable: true
  76473. });
  76474. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  76475. /**
  76476. * Gets the contrast used in the effect.
  76477. */
  76478. get: function () {
  76479. return this._contrast;
  76480. },
  76481. /**
  76482. * Sets the contrast used in the effect.
  76483. */
  76484. set: function (value) {
  76485. if (this._contrast === value) {
  76486. return;
  76487. }
  76488. this._contrast = value;
  76489. this._updateParameters();
  76490. },
  76491. enumerable: true,
  76492. configurable: true
  76493. });
  76494. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  76495. /**
  76496. * Gets the vignette blend mode allowing different kind of effect.
  76497. */
  76498. get: function () {
  76499. return this._vignetteBlendMode;
  76500. },
  76501. /**
  76502. * Sets the vignette blend mode allowing different kind of effect.
  76503. */
  76504. set: function (value) {
  76505. if (this._vignetteBlendMode === value) {
  76506. return;
  76507. }
  76508. this._vignetteBlendMode = value;
  76509. this._updateParameters();
  76510. },
  76511. enumerable: true,
  76512. configurable: true
  76513. });
  76514. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  76515. /**
  76516. * Gets wether the vignette effect is enabled.
  76517. */
  76518. get: function () {
  76519. return this._vignetteEnabled;
  76520. },
  76521. /**
  76522. * Sets wether the vignette effect is enabled.
  76523. */
  76524. set: function (value) {
  76525. if (this._vignetteEnabled === value) {
  76526. return;
  76527. }
  76528. this._vignetteEnabled = value;
  76529. this._updateParameters();
  76530. },
  76531. enumerable: true,
  76532. configurable: true
  76533. });
  76534. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  76535. /**
  76536. * Gets wether the image processing is applied through a post process or not.
  76537. */
  76538. get: function () {
  76539. return this._applyByPostProcess;
  76540. },
  76541. /**
  76542. * Sets wether the image processing is applied through a post process or not.
  76543. */
  76544. set: function (value) {
  76545. if (this._applyByPostProcess === value) {
  76546. return;
  76547. }
  76548. this._applyByPostProcess = value;
  76549. this._updateParameters();
  76550. },
  76551. enumerable: true,
  76552. configurable: true
  76553. });
  76554. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  76555. /**
  76556. * Gets wether the image processing is enabled or not.
  76557. */
  76558. get: function () {
  76559. return this._isEnabled;
  76560. },
  76561. /**
  76562. * Sets wether the image processing is enabled or not.
  76563. */
  76564. set: function (value) {
  76565. if (this._isEnabled === value) {
  76566. return;
  76567. }
  76568. this._isEnabled = value;
  76569. this._updateParameters();
  76570. },
  76571. enumerable: true,
  76572. configurable: true
  76573. });
  76574. /**
  76575. * Method called each time the image processing information changes requires to recompile the effect.
  76576. */
  76577. ImageProcessingConfiguration.prototype._updateParameters = function () {
  76578. this.onUpdateParameters.notifyObservers(this);
  76579. };
  76580. ImageProcessingConfiguration.prototype.getClassName = function () {
  76581. return "ImageProcessingConfiguration";
  76582. };
  76583. /**
  76584. * Prepare the list of uniforms associated with the Image Processing effects.
  76585. * @param uniformsList The list of uniforms used in the effect
  76586. * @param defines the list of defines currently in use
  76587. */
  76588. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  76589. if (defines.EXPOSURE) {
  76590. uniforms.push("exposureLinear");
  76591. }
  76592. if (defines.CONTRAST) {
  76593. uniforms.push("contrast");
  76594. }
  76595. if (defines.COLORGRADING) {
  76596. uniforms.push("colorTransformSettings");
  76597. }
  76598. if (defines.VIGNETTE) {
  76599. uniforms.push("vInverseScreenSize");
  76600. uniforms.push("vignetteSettings1");
  76601. uniforms.push("vignetteSettings2");
  76602. }
  76603. if (defines.COLORCURVES) {
  76604. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  76605. }
  76606. };
  76607. /**
  76608. * Prepare the list of samplers associated with the Image Processing effects.
  76609. * @param uniformsList The list of uniforms used in the effect
  76610. * @param defines the list of defines currently in use
  76611. */
  76612. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  76613. if (defines.COLORGRADING) {
  76614. samplersList.push("txColorTransform");
  76615. }
  76616. };
  76617. /**
  76618. * Prepare the list of defines associated to the shader.
  76619. * @param defines the list of defines to complete
  76620. */
  76621. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  76622. if (forPostProcess === void 0) { forPostProcess = false; }
  76623. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  76624. defines.VIGNETTE = false;
  76625. defines.TONEMAPPING = false;
  76626. defines.CONTRAST = false;
  76627. defines.EXPOSURE = false;
  76628. defines.COLORCURVES = false;
  76629. defines.COLORGRADING = false;
  76630. defines.COLORGRADING3D = false;
  76631. defines.IMAGEPROCESSING = false;
  76632. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  76633. return;
  76634. }
  76635. defines.VIGNETTE = this.vignetteEnabled;
  76636. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  76637. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  76638. defines.TONEMAPPING = this.toneMappingEnabled;
  76639. defines.CONTRAST = (this.contrast !== 1.0);
  76640. defines.EXPOSURE = (this.exposure !== 1.0);
  76641. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  76642. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  76643. if (defines.COLORGRADING) {
  76644. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  76645. }
  76646. else {
  76647. defines.COLORGRADING3D = false;
  76648. }
  76649. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  76650. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  76651. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  76652. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  76653. };
  76654. /**
  76655. * Returns true if all the image processing information are ready.
  76656. */
  76657. ImageProcessingConfiguration.prototype.isReady = function () {
  76658. // Color Grading texure can not be none blocking.
  76659. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  76660. };
  76661. /**
  76662. * Binds the image processing to the shader.
  76663. * @param effect The effect to bind to
  76664. */
  76665. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  76666. if (aspectRatio === void 0) { aspectRatio = 1; }
  76667. // Color Curves
  76668. if (this._colorCurvesEnabled && this.colorCurves) {
  76669. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  76670. }
  76671. // Vignette
  76672. if (this._vignetteEnabled) {
  76673. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  76674. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  76675. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  76676. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  76677. var vignetteScaleX = vignetteScaleY * aspectRatio;
  76678. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  76679. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  76680. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  76681. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  76682. var vignettePower = -2.0 * this.vignetteWeight;
  76683. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  76684. }
  76685. // Exposure
  76686. effect.setFloat("exposureLinear", this.exposure);
  76687. // Contrast
  76688. effect.setFloat("contrast", this.contrast);
  76689. // Color transform settings
  76690. if (this.colorGradingTexture) {
  76691. effect.setTexture("txColorTransform", this.colorGradingTexture);
  76692. var textureSize = this.colorGradingTexture.getSize().height;
  76693. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  76694. 0.5 / textureSize, // textureOffset
  76695. textureSize, // textureSize
  76696. this.colorGradingTexture.level // weight
  76697. );
  76698. }
  76699. };
  76700. /**
  76701. * Clones the current image processing instance.
  76702. * @return The cloned image processing
  76703. */
  76704. ImageProcessingConfiguration.prototype.clone = function () {
  76705. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  76706. };
  76707. /**
  76708. * Serializes the current image processing instance to a json representation.
  76709. * @return a JSON representation
  76710. */
  76711. ImageProcessingConfiguration.prototype.serialize = function () {
  76712. return BABYLON.SerializationHelper.Serialize(this);
  76713. };
  76714. /**
  76715. * Parses the image processing from a json representation.
  76716. * @param source the JSON source to parse
  76717. * @return The parsed image processing
  76718. */
  76719. ImageProcessingConfiguration.Parse = function (source) {
  76720. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  76721. };
  76722. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  76723. /**
  76724. * Used to apply the vignette as a mix with the pixel color.
  76725. */
  76726. get: function () {
  76727. return this._VIGNETTEMODE_MULTIPLY;
  76728. },
  76729. enumerable: true,
  76730. configurable: true
  76731. });
  76732. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  76733. /**
  76734. * Used to apply the vignette as a replacement of the pixel color.
  76735. */
  76736. get: function () {
  76737. return this._VIGNETTEMODE_OPAQUE;
  76738. },
  76739. enumerable: true,
  76740. configurable: true
  76741. });
  76742. // Static constants associated to the image processing.
  76743. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  76744. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  76745. __decorate([
  76746. BABYLON.serializeAsColorCurves()
  76747. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  76748. __decorate([
  76749. BABYLON.serialize()
  76750. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  76751. __decorate([
  76752. BABYLON.serializeAsTexture()
  76753. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  76754. __decorate([
  76755. BABYLON.serialize()
  76756. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  76757. __decorate([
  76758. BABYLON.serialize()
  76759. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  76760. __decorate([
  76761. BABYLON.serialize()
  76762. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  76763. __decorate([
  76764. BABYLON.serialize()
  76765. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  76766. __decorate([
  76767. BABYLON.serialize()
  76768. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  76769. __decorate([
  76770. BABYLON.serialize()
  76771. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  76772. __decorate([
  76773. BABYLON.serialize()
  76774. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  76775. __decorate([
  76776. BABYLON.serialize()
  76777. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  76778. __decorate([
  76779. BABYLON.serialize()
  76780. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  76781. __decorate([
  76782. BABYLON.serialize()
  76783. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  76784. __decorate([
  76785. BABYLON.serializeAsColor4()
  76786. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  76787. __decorate([
  76788. BABYLON.serialize()
  76789. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  76790. __decorate([
  76791. BABYLON.serialize()
  76792. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  76793. __decorate([
  76794. BABYLON.serialize()
  76795. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  76796. __decorate([
  76797. BABYLON.serialize()
  76798. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  76799. __decorate([
  76800. BABYLON.serialize()
  76801. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  76802. return ImageProcessingConfiguration;
  76803. }());
  76804. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  76805. })(BABYLON || (BABYLON = {}));
  76806. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  76807. var BABYLON;
  76808. (function (BABYLON) {
  76809. /**
  76810. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  76811. * It can help converting any input color in a desired output one. This can then be used to create effects
  76812. * from sepia, black and white to sixties or futuristic rendering...
  76813. *
  76814. * The only supported format is currently 3dl.
  76815. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  76816. */
  76817. var ColorGradingTexture = /** @class */ (function (_super) {
  76818. __extends(ColorGradingTexture, _super);
  76819. /**
  76820. * Instantiates a ColorGradingTexture from the following parameters.
  76821. *
  76822. * @param url The location of the color gradind data (currently only supporting 3dl)
  76823. * @param scene The scene the texture will be used in
  76824. */
  76825. function ColorGradingTexture(url, scene) {
  76826. var _this = _super.call(this, scene) || this;
  76827. if (!url) {
  76828. return _this;
  76829. }
  76830. _this._engine = scene.getEngine();
  76831. _this._textureMatrix = BABYLON.Matrix.Identity();
  76832. _this.name = url;
  76833. _this.url = url;
  76834. _this.hasAlpha = false;
  76835. _this.isCube = false;
  76836. _this.is3D = _this._engine.webGLVersion > 1;
  76837. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76838. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76839. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76840. _this.anisotropicFilteringLevel = 1;
  76841. _this._texture = _this._getFromCache(url, true);
  76842. if (!_this._texture) {
  76843. if (!scene.useDelayedTextureLoading) {
  76844. _this.loadTexture();
  76845. }
  76846. else {
  76847. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  76848. }
  76849. }
  76850. return _this;
  76851. }
  76852. /**
  76853. * Returns the texture matrix used in most of the material.
  76854. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  76855. */
  76856. ColorGradingTexture.prototype.getTextureMatrix = function () {
  76857. return this._textureMatrix;
  76858. };
  76859. /**
  76860. * Occurs when the file being loaded is a .3dl LUT file.
  76861. */
  76862. ColorGradingTexture.prototype.load3dlTexture = function () {
  76863. var engine = this._engine;
  76864. var texture;
  76865. if (engine.webGLVersion === 1) {
  76866. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76867. }
  76868. else {
  76869. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76870. }
  76871. this._texture = texture;
  76872. var callback = function (text) {
  76873. if (typeof text !== "string") {
  76874. return;
  76875. }
  76876. var data = null;
  76877. var tempData = null;
  76878. var line;
  76879. var lines = text.split('\n');
  76880. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  76881. var maxColor = 0;
  76882. for (var i = 0; i < lines.length; i++) {
  76883. line = lines[i];
  76884. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  76885. continue;
  76886. if (line.indexOf('#') === 0)
  76887. continue;
  76888. var words = line.split(" ");
  76889. if (size === 0) {
  76890. // Number of space + one
  76891. size = words.length;
  76892. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  76893. tempData = new Float32Array(size * size * size * 4);
  76894. continue;
  76895. }
  76896. if (size != 0) {
  76897. var r = Math.max(parseInt(words[0]), 0);
  76898. var g = Math.max(parseInt(words[1]), 0);
  76899. var b = Math.max(parseInt(words[2]), 0);
  76900. maxColor = Math.max(r, maxColor);
  76901. maxColor = Math.max(g, maxColor);
  76902. maxColor = Math.max(b, maxColor);
  76903. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  76904. if (tempData) {
  76905. tempData[pixelStorageIndex + 0] = r;
  76906. tempData[pixelStorageIndex + 1] = g;
  76907. tempData[pixelStorageIndex + 2] = b;
  76908. }
  76909. pixelIndexSlice++;
  76910. if (pixelIndexSlice % size == 0) {
  76911. pixelIndexH++;
  76912. pixelIndexSlice = 0;
  76913. if (pixelIndexH % size == 0) {
  76914. pixelIndexW++;
  76915. pixelIndexH = 0;
  76916. }
  76917. }
  76918. }
  76919. }
  76920. if (tempData && data) {
  76921. for (var i = 0; i < tempData.length; i++) {
  76922. if (i > 0 && (i + 1) % 4 === 0) {
  76923. data[i] = 255;
  76924. }
  76925. else {
  76926. var value = tempData[i];
  76927. data[i] = (value / maxColor * 255);
  76928. }
  76929. }
  76930. }
  76931. if (texture.is3D) {
  76932. texture.updateSize(size, size, size);
  76933. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  76934. }
  76935. else {
  76936. texture.updateSize(size * size, size);
  76937. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  76938. }
  76939. };
  76940. var scene = this.getScene();
  76941. if (scene) {
  76942. scene._loadFile(this.url, callback);
  76943. }
  76944. else {
  76945. this._engine._loadFile(this.url, callback);
  76946. }
  76947. return this._texture;
  76948. };
  76949. /**
  76950. * Starts the loading process of the texture.
  76951. */
  76952. ColorGradingTexture.prototype.loadTexture = function () {
  76953. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  76954. this.load3dlTexture();
  76955. }
  76956. };
  76957. /**
  76958. * Clones the color gradind texture.
  76959. */
  76960. ColorGradingTexture.prototype.clone = function () {
  76961. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  76962. // Base texture
  76963. newTexture.level = this.level;
  76964. return newTexture;
  76965. };
  76966. /**
  76967. * Called during delayed load for textures.
  76968. */
  76969. ColorGradingTexture.prototype.delayLoad = function () {
  76970. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  76971. return;
  76972. }
  76973. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  76974. this._texture = this._getFromCache(this.url, true);
  76975. if (!this._texture) {
  76976. this.loadTexture();
  76977. }
  76978. };
  76979. /**
  76980. * Parses a color grading texture serialized by Babylon.
  76981. * @param parsedTexture The texture information being parsedTexture
  76982. * @param scene The scene to load the texture in
  76983. * @param rootUrl The root url of the data assets to load
  76984. * @return A color gradind texture
  76985. */
  76986. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  76987. var texture = null;
  76988. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  76989. texture = new ColorGradingTexture(parsedTexture.name, scene);
  76990. texture.name = parsedTexture.name;
  76991. texture.level = parsedTexture.level;
  76992. }
  76993. return texture;
  76994. };
  76995. /**
  76996. * Serializes the LUT texture to json format.
  76997. */
  76998. ColorGradingTexture.prototype.serialize = function () {
  76999. if (!this.name) {
  77000. return null;
  77001. }
  77002. var serializationObject = {};
  77003. serializationObject.name = this.name;
  77004. serializationObject.level = this.level;
  77005. serializationObject.customType = "BABYLON.ColorGradingTexture";
  77006. return serializationObject;
  77007. };
  77008. /**
  77009. * Empty line regex stored for GC.
  77010. */
  77011. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  77012. return ColorGradingTexture;
  77013. }(BABYLON.BaseTexture));
  77014. BABYLON.ColorGradingTexture = ColorGradingTexture;
  77015. })(BABYLON || (BABYLON = {}));
  77016. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  77017. var BABYLON;
  77018. (function (BABYLON) {
  77019. /**
  77020. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  77021. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  77022. * 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;
  77023. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  77024. */
  77025. var ColorCurves = /** @class */ (function () {
  77026. function ColorCurves() {
  77027. this._dirty = true;
  77028. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  77029. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  77030. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  77031. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  77032. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  77033. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  77034. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  77035. this._globalHue = 30;
  77036. this._globalDensity = 0;
  77037. this._globalSaturation = 0;
  77038. this._globalExposure = 0;
  77039. this._highlightsHue = 30;
  77040. this._highlightsDensity = 0;
  77041. this._highlightsSaturation = 0;
  77042. this._highlightsExposure = 0;
  77043. this._midtonesHue = 30;
  77044. this._midtonesDensity = 0;
  77045. this._midtonesSaturation = 0;
  77046. this._midtonesExposure = 0;
  77047. this._shadowsHue = 30;
  77048. this._shadowsDensity = 0;
  77049. this._shadowsSaturation = 0;
  77050. this._shadowsExposure = 0;
  77051. }
  77052. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  77053. /**
  77054. * Gets the global Hue value.
  77055. * 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).
  77056. */
  77057. get: function () {
  77058. return this._globalHue;
  77059. },
  77060. /**
  77061. * Sets the global Hue value.
  77062. * 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).
  77063. */
  77064. set: function (value) {
  77065. this._globalHue = value;
  77066. this._dirty = true;
  77067. },
  77068. enumerable: true,
  77069. configurable: true
  77070. });
  77071. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  77072. /**
  77073. * Gets the global Density value.
  77074. * 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.
  77075. * Values less than zero provide a filter of opposite hue.
  77076. */
  77077. get: function () {
  77078. return this._globalDensity;
  77079. },
  77080. /**
  77081. * Sets the global Density value.
  77082. * 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.
  77083. * Values less than zero provide a filter of opposite hue.
  77084. */
  77085. set: function (value) {
  77086. this._globalDensity = value;
  77087. this._dirty = true;
  77088. },
  77089. enumerable: true,
  77090. configurable: true
  77091. });
  77092. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  77093. /**
  77094. * Gets the global Saturation value.
  77095. * 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.
  77096. */
  77097. get: function () {
  77098. return this._globalSaturation;
  77099. },
  77100. /**
  77101. * Sets the global Saturation value.
  77102. * 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.
  77103. */
  77104. set: function (value) {
  77105. this._globalSaturation = value;
  77106. this._dirty = true;
  77107. },
  77108. enumerable: true,
  77109. configurable: true
  77110. });
  77111. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  77112. /**
  77113. * Gets the global Exposure value.
  77114. * 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.
  77115. */
  77116. get: function () {
  77117. return this._globalExposure;
  77118. },
  77119. /**
  77120. * Sets the global Exposure value.
  77121. * 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.
  77122. */
  77123. set: function (value) {
  77124. this._globalExposure = value;
  77125. this._dirty = true;
  77126. },
  77127. enumerable: true,
  77128. configurable: true
  77129. });
  77130. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  77131. /**
  77132. * Gets the highlights Hue value.
  77133. * 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).
  77134. */
  77135. get: function () {
  77136. return this._highlightsHue;
  77137. },
  77138. /**
  77139. * Sets the highlights Hue value.
  77140. * 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).
  77141. */
  77142. set: function (value) {
  77143. this._highlightsHue = value;
  77144. this._dirty = true;
  77145. },
  77146. enumerable: true,
  77147. configurable: true
  77148. });
  77149. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  77150. /**
  77151. * Gets the highlights Density value.
  77152. * 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.
  77153. * Values less than zero provide a filter of opposite hue.
  77154. */
  77155. get: function () {
  77156. return this._highlightsDensity;
  77157. },
  77158. /**
  77159. * Sets the highlights Density value.
  77160. * 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.
  77161. * Values less than zero provide a filter of opposite hue.
  77162. */
  77163. set: function (value) {
  77164. this._highlightsDensity = value;
  77165. this._dirty = true;
  77166. },
  77167. enumerable: true,
  77168. configurable: true
  77169. });
  77170. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  77171. /**
  77172. * Gets the highlights Saturation value.
  77173. * 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.
  77174. */
  77175. get: function () {
  77176. return this._highlightsSaturation;
  77177. },
  77178. /**
  77179. * Sets the highlights Saturation value.
  77180. * 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.
  77181. */
  77182. set: function (value) {
  77183. this._highlightsSaturation = value;
  77184. this._dirty = true;
  77185. },
  77186. enumerable: true,
  77187. configurable: true
  77188. });
  77189. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  77190. /**
  77191. * Gets the highlights Exposure value.
  77192. * 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.
  77193. */
  77194. get: function () {
  77195. return this._highlightsExposure;
  77196. },
  77197. /**
  77198. * Sets the highlights Exposure value.
  77199. * 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.
  77200. */
  77201. set: function (value) {
  77202. this._highlightsExposure = value;
  77203. this._dirty = true;
  77204. },
  77205. enumerable: true,
  77206. configurable: true
  77207. });
  77208. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  77209. /**
  77210. * Gets the midtones Hue value.
  77211. * 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).
  77212. */
  77213. get: function () {
  77214. return this._midtonesHue;
  77215. },
  77216. /**
  77217. * Sets the midtones Hue value.
  77218. * 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).
  77219. */
  77220. set: function (value) {
  77221. this._midtonesHue = value;
  77222. this._dirty = true;
  77223. },
  77224. enumerable: true,
  77225. configurable: true
  77226. });
  77227. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  77228. /**
  77229. * Gets the midtones Density value.
  77230. * 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.
  77231. * Values less than zero provide a filter of opposite hue.
  77232. */
  77233. get: function () {
  77234. return this._midtonesDensity;
  77235. },
  77236. /**
  77237. * Sets the midtones Density value.
  77238. * 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.
  77239. * Values less than zero provide a filter of opposite hue.
  77240. */
  77241. set: function (value) {
  77242. this._midtonesDensity = value;
  77243. this._dirty = true;
  77244. },
  77245. enumerable: true,
  77246. configurable: true
  77247. });
  77248. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  77249. /**
  77250. * Gets the midtones Saturation value.
  77251. * 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.
  77252. */
  77253. get: function () {
  77254. return this._midtonesSaturation;
  77255. },
  77256. /**
  77257. * Sets the midtones Saturation value.
  77258. * 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.
  77259. */
  77260. set: function (value) {
  77261. this._midtonesSaturation = value;
  77262. this._dirty = true;
  77263. },
  77264. enumerable: true,
  77265. configurable: true
  77266. });
  77267. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  77268. /**
  77269. * Gets the midtones Exposure value.
  77270. * 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.
  77271. */
  77272. get: function () {
  77273. return this._midtonesExposure;
  77274. },
  77275. /**
  77276. * Sets the midtones Exposure value.
  77277. * 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.
  77278. */
  77279. set: function (value) {
  77280. this._midtonesExposure = value;
  77281. this._dirty = true;
  77282. },
  77283. enumerable: true,
  77284. configurable: true
  77285. });
  77286. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  77287. /**
  77288. * Gets the shadows Hue value.
  77289. * 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).
  77290. */
  77291. get: function () {
  77292. return this._shadowsHue;
  77293. },
  77294. /**
  77295. * Sets the shadows Hue value.
  77296. * 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).
  77297. */
  77298. set: function (value) {
  77299. this._shadowsHue = value;
  77300. this._dirty = true;
  77301. },
  77302. enumerable: true,
  77303. configurable: true
  77304. });
  77305. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  77306. /**
  77307. * Gets the shadows Density value.
  77308. * 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.
  77309. * Values less than zero provide a filter of opposite hue.
  77310. */
  77311. get: function () {
  77312. return this._shadowsDensity;
  77313. },
  77314. /**
  77315. * Sets the shadows Density value.
  77316. * 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.
  77317. * Values less than zero provide a filter of opposite hue.
  77318. */
  77319. set: function (value) {
  77320. this._shadowsDensity = value;
  77321. this._dirty = true;
  77322. },
  77323. enumerable: true,
  77324. configurable: true
  77325. });
  77326. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  77327. /**
  77328. * Gets the shadows Saturation value.
  77329. * 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.
  77330. */
  77331. get: function () {
  77332. return this._shadowsSaturation;
  77333. },
  77334. /**
  77335. * Sets the shadows Saturation value.
  77336. * 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.
  77337. */
  77338. set: function (value) {
  77339. this._shadowsSaturation = value;
  77340. this._dirty = true;
  77341. },
  77342. enumerable: true,
  77343. configurable: true
  77344. });
  77345. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  77346. /**
  77347. * Gets the shadows Exposure value.
  77348. * 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.
  77349. */
  77350. get: function () {
  77351. return this._shadowsExposure;
  77352. },
  77353. /**
  77354. * Sets the shadows Exposure value.
  77355. * 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.
  77356. */
  77357. set: function (value) {
  77358. this._shadowsExposure = value;
  77359. this._dirty = true;
  77360. },
  77361. enumerable: true,
  77362. configurable: true
  77363. });
  77364. ColorCurves.prototype.getClassName = function () {
  77365. return "ColorCurves";
  77366. };
  77367. /**
  77368. * Binds the color curves to the shader.
  77369. * @param colorCurves The color curve to bind
  77370. * @param effect The effect to bind to
  77371. */
  77372. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  77373. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  77374. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  77375. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  77376. if (colorCurves._dirty) {
  77377. colorCurves._dirty = false;
  77378. // Fill in global info.
  77379. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  77380. // Compute highlights info.
  77381. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  77382. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  77383. // Compute midtones info.
  77384. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  77385. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  77386. // Compute shadows info.
  77387. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  77388. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  77389. // Compute deltas (neutral is midtones).
  77390. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  77391. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  77392. }
  77393. if (effect) {
  77394. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  77395. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  77396. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  77397. }
  77398. };
  77399. /**
  77400. * Prepare the list of uniforms associated with the ColorCurves effects.
  77401. * @param uniformsList The list of uniforms used in the effect
  77402. */
  77403. ColorCurves.PrepareUniforms = function (uniformsList) {
  77404. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  77405. };
  77406. /**
  77407. * Returns color grading data based on a hue, density, saturation and exposure value.
  77408. * @param filterHue The hue of the color filter.
  77409. * @param filterDensity The density of the color filter.
  77410. * @param saturation The saturation.
  77411. * @param exposure The exposure.
  77412. * @param result The result data container.
  77413. */
  77414. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  77415. if (hue == null) {
  77416. return;
  77417. }
  77418. hue = ColorCurves.clamp(hue, 0, 360);
  77419. density = ColorCurves.clamp(density, -100, 100);
  77420. saturation = ColorCurves.clamp(saturation, -100, 100);
  77421. exposure = ColorCurves.clamp(exposure, -100, 100);
  77422. // Remap the slider/config filter density with non-linear mapping and also scale by half
  77423. // so that the maximum filter density is only 50% control. This provides fine control
  77424. // for small values and reasonable range.
  77425. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  77426. density *= 0.5;
  77427. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  77428. if (density < 0) {
  77429. density *= -1;
  77430. hue = (hue + 180) % 360;
  77431. }
  77432. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  77433. result.scaleToRef(2, result);
  77434. result.a = 1 + 0.01 * saturation;
  77435. };
  77436. /**
  77437. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  77438. * @param value The input slider value in range [-100,100].
  77439. * @returns Adjusted value.
  77440. */
  77441. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  77442. value /= 100;
  77443. var x = Math.abs(value);
  77444. x = Math.pow(x, 2);
  77445. if (value < 0) {
  77446. x *= -1;
  77447. }
  77448. x *= 100;
  77449. return x;
  77450. };
  77451. /**
  77452. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  77453. * @param hue The hue (H) input.
  77454. * @param saturation The saturation (S) input.
  77455. * @param brightness The brightness (B) input.
  77456. * @result An RGBA color represented as Vector4.
  77457. */
  77458. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  77459. var h = ColorCurves.clamp(hue, 0, 360);
  77460. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  77461. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  77462. if (s === 0) {
  77463. result.r = v;
  77464. result.g = v;
  77465. result.b = v;
  77466. }
  77467. else {
  77468. // sector 0 to 5
  77469. h /= 60;
  77470. var i = Math.floor(h);
  77471. // fractional part of h
  77472. var f = h - i;
  77473. var p = v * (1 - s);
  77474. var q = v * (1 - s * f);
  77475. var t = v * (1 - s * (1 - f));
  77476. switch (i) {
  77477. case 0:
  77478. result.r = v;
  77479. result.g = t;
  77480. result.b = p;
  77481. break;
  77482. case 1:
  77483. result.r = q;
  77484. result.g = v;
  77485. result.b = p;
  77486. break;
  77487. case 2:
  77488. result.r = p;
  77489. result.g = v;
  77490. result.b = t;
  77491. break;
  77492. case 3:
  77493. result.r = p;
  77494. result.g = q;
  77495. result.b = v;
  77496. break;
  77497. case 4:
  77498. result.r = t;
  77499. result.g = p;
  77500. result.b = v;
  77501. break;
  77502. default: // case 5:
  77503. result.r = v;
  77504. result.g = p;
  77505. result.b = q;
  77506. break;
  77507. }
  77508. }
  77509. result.a = 1;
  77510. };
  77511. /**
  77512. * Returns a value clamped between min and max
  77513. * @param value The value to clamp
  77514. * @param min The minimum of value
  77515. * @param max The maximum of value
  77516. * @returns The clamped value.
  77517. */
  77518. ColorCurves.clamp = function (value, min, max) {
  77519. return Math.min(Math.max(value, min), max);
  77520. };
  77521. /**
  77522. * Clones the current color curve instance.
  77523. * @return The cloned curves
  77524. */
  77525. ColorCurves.prototype.clone = function () {
  77526. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  77527. };
  77528. /**
  77529. * Serializes the current color curve instance to a json representation.
  77530. * @return a JSON representation
  77531. */
  77532. ColorCurves.prototype.serialize = function () {
  77533. return BABYLON.SerializationHelper.Serialize(this);
  77534. };
  77535. /**
  77536. * Parses the color curve from a json representation.
  77537. * @param source the JSON source to parse
  77538. * @return The parsed curves
  77539. */
  77540. ColorCurves.Parse = function (source) {
  77541. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  77542. };
  77543. __decorate([
  77544. BABYLON.serialize()
  77545. ], ColorCurves.prototype, "_globalHue", void 0);
  77546. __decorate([
  77547. BABYLON.serialize()
  77548. ], ColorCurves.prototype, "_globalDensity", void 0);
  77549. __decorate([
  77550. BABYLON.serialize()
  77551. ], ColorCurves.prototype, "_globalSaturation", void 0);
  77552. __decorate([
  77553. BABYLON.serialize()
  77554. ], ColorCurves.prototype, "_globalExposure", void 0);
  77555. __decorate([
  77556. BABYLON.serialize()
  77557. ], ColorCurves.prototype, "_highlightsHue", void 0);
  77558. __decorate([
  77559. BABYLON.serialize()
  77560. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  77561. __decorate([
  77562. BABYLON.serialize()
  77563. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  77564. __decorate([
  77565. BABYLON.serialize()
  77566. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  77567. __decorate([
  77568. BABYLON.serialize()
  77569. ], ColorCurves.prototype, "_midtonesHue", void 0);
  77570. __decorate([
  77571. BABYLON.serialize()
  77572. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  77573. __decorate([
  77574. BABYLON.serialize()
  77575. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  77576. __decorate([
  77577. BABYLON.serialize()
  77578. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  77579. return ColorCurves;
  77580. }());
  77581. BABYLON.ColorCurves = ColorCurves;
  77582. })(BABYLON || (BABYLON = {}));
  77583. //# sourceMappingURL=babylon.colorCurves.js.map
  77584. var BABYLON;
  77585. (function (BABYLON) {
  77586. var RefractionPostProcess = /** @class */ (function (_super) {
  77587. __extends(RefractionPostProcess, _super);
  77588. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  77589. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  77590. _this.color = color;
  77591. _this.depth = depth;
  77592. _this.colorLevel = colorLevel;
  77593. _this._ownRefractionTexture = true;
  77594. _this.onActivateObservable.add(function (cam) {
  77595. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  77596. });
  77597. _this.onApplyObservable.add(function (effect) {
  77598. effect.setColor3("baseColor", _this.color);
  77599. effect.setFloat("depth", _this.depth);
  77600. effect.setFloat("colorLevel", _this.colorLevel);
  77601. effect.setTexture("refractionSampler", _this._refTexture);
  77602. });
  77603. return _this;
  77604. }
  77605. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  77606. /**
  77607. * Gets or sets the refraction texture
  77608. * Please note that you are responsible for disposing the texture if you set it manually
  77609. */
  77610. get: function () {
  77611. return this._refTexture;
  77612. },
  77613. set: function (value) {
  77614. if (this._refTexture && this._ownRefractionTexture) {
  77615. this._refTexture.dispose();
  77616. }
  77617. this._refTexture = value;
  77618. this._ownRefractionTexture = false;
  77619. },
  77620. enumerable: true,
  77621. configurable: true
  77622. });
  77623. // Methods
  77624. RefractionPostProcess.prototype.dispose = function (camera) {
  77625. if (this._refTexture && this._ownRefractionTexture) {
  77626. this._refTexture.dispose();
  77627. this._refTexture = null;
  77628. }
  77629. _super.prototype.dispose.call(this, camera);
  77630. };
  77631. return RefractionPostProcess;
  77632. }(BABYLON.PostProcess));
  77633. BABYLON.RefractionPostProcess = RefractionPostProcess;
  77634. })(BABYLON || (BABYLON = {}));
  77635. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  77636. var BABYLON;
  77637. (function (BABYLON) {
  77638. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  77639. __extends(BlackAndWhitePostProcess, _super);
  77640. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  77641. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  77642. _this.degree = 1;
  77643. _this.onApplyObservable.add(function (effect) {
  77644. effect.setFloat("degree", _this.degree);
  77645. });
  77646. return _this;
  77647. }
  77648. return BlackAndWhitePostProcess;
  77649. }(BABYLON.PostProcess));
  77650. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  77651. })(BABYLON || (BABYLON = {}));
  77652. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  77653. var BABYLON;
  77654. (function (BABYLON) {
  77655. /**
  77656. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  77657. * input texture to perform effects such as edge detection or sharpening
  77658. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  77659. */
  77660. var ConvolutionPostProcess = /** @class */ (function (_super) {
  77661. __extends(ConvolutionPostProcess, _super);
  77662. /**
  77663. * Creates a new instance ConvolutionPostProcess
  77664. * @param name The name of the effect.
  77665. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  77666. * @param options The required width/height ratio to downsize to before computing the render pass.
  77667. * @param camera The camera to apply the render pass to.
  77668. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77669. * @param engine The engine which the post process will be applied. (default: current engine)
  77670. * @param reusable If the post process can be reused on the same frame. (default: false)
  77671. * @param textureType Type of textures used when performing the post process. (default: 0)
  77672. */
  77673. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  77674. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77675. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77676. _this.kernel = kernel;
  77677. _this.onApply = function (effect) {
  77678. effect.setFloat2("screenSize", _this.width, _this.height);
  77679. effect.setArray("kernel", _this.kernel);
  77680. };
  77681. return _this;
  77682. }
  77683. // Statics
  77684. /**
  77685. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77686. */
  77687. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  77688. /**
  77689. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77690. */
  77691. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  77692. /**
  77693. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77694. */
  77695. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  77696. /**
  77697. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77698. */
  77699. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  77700. /**
  77701. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77702. */
  77703. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  77704. /**
  77705. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77706. */
  77707. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  77708. return ConvolutionPostProcess;
  77709. }(BABYLON.PostProcess));
  77710. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  77711. })(BABYLON || (BABYLON = {}));
  77712. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  77713. var BABYLON;
  77714. (function (BABYLON) {
  77715. var FilterPostProcess = /** @class */ (function (_super) {
  77716. __extends(FilterPostProcess, _super);
  77717. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  77718. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  77719. _this.kernelMatrix = kernelMatrix;
  77720. _this.onApply = function (effect) {
  77721. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  77722. };
  77723. return _this;
  77724. }
  77725. return FilterPostProcess;
  77726. }(BABYLON.PostProcess));
  77727. BABYLON.FilterPostProcess = FilterPostProcess;
  77728. })(BABYLON || (BABYLON = {}));
  77729. //# sourceMappingURL=babylon.filterPostProcess.js.map
  77730. var BABYLON;
  77731. (function (BABYLON) {
  77732. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  77733. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  77734. __extends(VolumetricLightScatteringPostProcess, _super);
  77735. /**
  77736. * @constructor
  77737. * @param {string} name - The post-process name
  77738. * @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)
  77739. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  77740. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  77741. * @param {number} samples - The post-process quality, default 100
  77742. * @param {number} samplingMode - The post-process filtering mode
  77743. * @param {BABYLON.Engine} engine - The babylon engine
  77744. * @param {boolean} reusable - If the post-process is reusable
  77745. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  77746. */
  77747. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  77748. if (samples === void 0) { samples = 100; }
  77749. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77750. 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;
  77751. _this._screenCoordinates = BABYLON.Vector2.Zero();
  77752. /**
  77753. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  77754. */
  77755. _this.customMeshPosition = BABYLON.Vector3.Zero();
  77756. /**
  77757. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  77758. */
  77759. _this.useCustomMeshPosition = false;
  77760. /**
  77761. * If the post-process should inverse the light scattering direction
  77762. */
  77763. _this.invert = true;
  77764. /**
  77765. * Array containing the excluded meshes not rendered in the internal pass
  77766. */
  77767. _this.excludedMeshes = new Array();
  77768. /**
  77769. * Controls the overall intensity of the post-process
  77770. */
  77771. _this.exposure = 0.3;
  77772. /**
  77773. * Dissipates each sample's contribution in range [0, 1]
  77774. */
  77775. _this.decay = 0.96815;
  77776. /**
  77777. * Controls the overall intensity of each sample
  77778. */
  77779. _this.weight = 0.58767;
  77780. /**
  77781. * Controls the density of each sample
  77782. */
  77783. _this.density = 0.926;
  77784. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  77785. engine = scene.getEngine();
  77786. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  77787. // Configure mesh
  77788. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  77789. // Configure
  77790. _this._createPass(scene, ratio.passRatio || ratio);
  77791. _this.onActivate = function (camera) {
  77792. if (!_this.isSupported) {
  77793. _this.dispose(camera);
  77794. }
  77795. _this.onActivate = null;
  77796. };
  77797. _this.onApplyObservable.add(function (effect) {
  77798. _this._updateMeshScreenCoordinates(scene);
  77799. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  77800. effect.setFloat("exposure", _this.exposure);
  77801. effect.setFloat("decay", _this.decay);
  77802. effect.setFloat("weight", _this.weight);
  77803. effect.setFloat("density", _this.density);
  77804. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  77805. });
  77806. return _this;
  77807. }
  77808. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  77809. get: function () {
  77810. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77811. return false;
  77812. },
  77813. set: function (useDiffuseColor) {
  77814. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77815. },
  77816. enumerable: true,
  77817. configurable: true
  77818. });
  77819. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  77820. return "VolumetricLightScatteringPostProcess";
  77821. };
  77822. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  77823. var mesh = subMesh.getMesh();
  77824. // Render this.mesh as default
  77825. if (mesh === this.mesh && mesh.material) {
  77826. return mesh.material.isReady(mesh);
  77827. }
  77828. var defines = [];
  77829. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77830. var material = subMesh.getMaterial();
  77831. // Alpha test
  77832. if (material) {
  77833. if (material.needAlphaTesting()) {
  77834. defines.push("#define ALPHATEST");
  77835. }
  77836. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77837. attribs.push(BABYLON.VertexBuffer.UVKind);
  77838. defines.push("#define UV1");
  77839. }
  77840. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77841. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77842. defines.push("#define UV2");
  77843. }
  77844. }
  77845. // Bones
  77846. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77847. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77848. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77849. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77850. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  77851. }
  77852. else {
  77853. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77854. }
  77855. // Instances
  77856. if (useInstances) {
  77857. defines.push("#define INSTANCES");
  77858. attribs.push("world0");
  77859. attribs.push("world1");
  77860. attribs.push("world2");
  77861. attribs.push("world3");
  77862. }
  77863. // Get correct effect
  77864. var join = defines.join("\n");
  77865. if (this._cachedDefines !== join) {
  77866. this._cachedDefines = join;
  77867. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  77868. }
  77869. return this._volumetricLightScatteringPass.isReady();
  77870. };
  77871. /**
  77872. * Sets the new light position for light scattering effect
  77873. * @param {BABYLON.Vector3} The new custom light position
  77874. */
  77875. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  77876. this.customMeshPosition = position;
  77877. };
  77878. /**
  77879. * Returns the light position for light scattering effect
  77880. * @return {BABYLON.Vector3} The custom light position
  77881. */
  77882. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  77883. return this.customMeshPosition;
  77884. };
  77885. /**
  77886. * Disposes the internal assets and detaches the post-process from the camera
  77887. */
  77888. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  77889. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  77890. if (rttIndex !== -1) {
  77891. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  77892. }
  77893. this._volumetricLightScatteringRTT.dispose();
  77894. _super.prototype.dispose.call(this, camera);
  77895. };
  77896. /**
  77897. * Returns the render target texture used by the post-process
  77898. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  77899. */
  77900. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  77901. return this._volumetricLightScatteringRTT;
  77902. };
  77903. // Private methods
  77904. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  77905. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  77906. return true;
  77907. }
  77908. return false;
  77909. };
  77910. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  77911. var _this = this;
  77912. var engine = scene.getEngine();
  77913. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  77914. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77915. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77916. this._volumetricLightScatteringRTT.renderList = null;
  77917. this._volumetricLightScatteringRTT.renderParticles = false;
  77918. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  77919. var camera = this.getCamera();
  77920. if (camera) {
  77921. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77922. }
  77923. else {
  77924. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77925. }
  77926. // Custom render function for submeshes
  77927. var renderSubMesh = function (subMesh) {
  77928. var mesh = subMesh.getRenderingMesh();
  77929. if (_this._meshExcluded(mesh)) {
  77930. return;
  77931. }
  77932. var material = subMesh.getMaterial();
  77933. if (!material) {
  77934. return;
  77935. }
  77936. var scene = mesh.getScene();
  77937. var engine = scene.getEngine();
  77938. // Culling
  77939. engine.setState(material.backFaceCulling);
  77940. // Managing instances
  77941. var batch = mesh._getInstancesRenderList(subMesh._id);
  77942. if (batch.mustReturn) {
  77943. return;
  77944. }
  77945. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77946. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  77947. var effect = _this._volumetricLightScatteringPass;
  77948. if (mesh === _this.mesh) {
  77949. if (subMesh.effect) {
  77950. effect = subMesh.effect;
  77951. }
  77952. else {
  77953. effect = material.getEffect();
  77954. }
  77955. }
  77956. engine.enableEffect(effect);
  77957. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  77958. if (mesh === _this.mesh) {
  77959. material.bind(mesh.getWorldMatrix(), mesh);
  77960. }
  77961. else {
  77962. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  77963. // Alpha test
  77964. if (material && material.needAlphaTesting()) {
  77965. var alphaTexture = material.getAlphaTestTexture();
  77966. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  77967. if (alphaTexture) {
  77968. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77969. }
  77970. }
  77971. // Bones
  77972. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77973. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77974. }
  77975. }
  77976. // Draw
  77977. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  77978. }
  77979. };
  77980. // Render target texture callbacks
  77981. var savedSceneClearColor;
  77982. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  77983. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  77984. savedSceneClearColor = scene.clearColor;
  77985. scene.clearColor = sceneClearColor;
  77986. });
  77987. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  77988. scene.clearColor = savedSceneClearColor;
  77989. });
  77990. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77991. var engine = scene.getEngine();
  77992. var index;
  77993. if (depthOnlySubMeshes.length) {
  77994. engine.setColorWrite(false);
  77995. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77996. renderSubMesh(depthOnlySubMeshes.data[index]);
  77997. }
  77998. engine.setColorWrite(true);
  77999. }
  78000. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78001. renderSubMesh(opaqueSubMeshes.data[index]);
  78002. }
  78003. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78004. renderSubMesh(alphaTestSubMeshes.data[index]);
  78005. }
  78006. if (transparentSubMeshes.length) {
  78007. // Sort sub meshes
  78008. for (index = 0; index < transparentSubMeshes.length; index++) {
  78009. var submesh = transparentSubMeshes.data[index];
  78010. var boundingInfo = submesh.getBoundingInfo();
  78011. if (boundingInfo && scene.activeCamera) {
  78012. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  78013. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  78014. }
  78015. }
  78016. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  78017. sortedArray.sort(function (a, b) {
  78018. // Alpha index first
  78019. if (a._alphaIndex > b._alphaIndex) {
  78020. return 1;
  78021. }
  78022. if (a._alphaIndex < b._alphaIndex) {
  78023. return -1;
  78024. }
  78025. // Then distance to camera
  78026. if (a._distanceToCamera < b._distanceToCamera) {
  78027. return 1;
  78028. }
  78029. if (a._distanceToCamera > b._distanceToCamera) {
  78030. return -1;
  78031. }
  78032. return 0;
  78033. });
  78034. // Render sub meshes
  78035. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  78036. for (index = 0; index < sortedArray.length; index++) {
  78037. renderSubMesh(sortedArray[index]);
  78038. }
  78039. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  78040. }
  78041. };
  78042. };
  78043. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  78044. var transform = scene.getTransformMatrix();
  78045. var meshPosition;
  78046. if (this.useCustomMeshPosition) {
  78047. meshPosition = this.customMeshPosition;
  78048. }
  78049. else if (this.attachedNode) {
  78050. meshPosition = this.attachedNode.position;
  78051. }
  78052. else {
  78053. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  78054. }
  78055. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  78056. this._screenCoordinates.x = pos.x / this._viewPort.width;
  78057. this._screenCoordinates.y = pos.y / this._viewPort.height;
  78058. if (this.invert)
  78059. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  78060. };
  78061. // Static methods
  78062. /**
  78063. * Creates a default mesh for the Volumeric Light Scattering post-process
  78064. * @param {string} The mesh name
  78065. * @param {BABYLON.Scene} The scene where to create the mesh
  78066. * @return {BABYLON.Mesh} the default mesh
  78067. */
  78068. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  78069. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  78070. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  78071. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  78072. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  78073. mesh.material = material;
  78074. return mesh;
  78075. };
  78076. __decorate([
  78077. BABYLON.serializeAsVector3()
  78078. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  78079. __decorate([
  78080. BABYLON.serialize()
  78081. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  78082. __decorate([
  78083. BABYLON.serialize()
  78084. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  78085. __decorate([
  78086. BABYLON.serializeAsMeshReference()
  78087. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  78088. __decorate([
  78089. BABYLON.serialize()
  78090. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  78091. __decorate([
  78092. BABYLON.serialize()
  78093. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  78094. __decorate([
  78095. BABYLON.serialize()
  78096. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  78097. __decorate([
  78098. BABYLON.serialize()
  78099. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  78100. __decorate([
  78101. BABYLON.serialize()
  78102. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  78103. return VolumetricLightScatteringPostProcess;
  78104. }(BABYLON.PostProcess));
  78105. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  78106. })(BABYLON || (BABYLON = {}));
  78107. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  78108. //
  78109. // This post-process allows the modification of rendered colors by using
  78110. // a 'look-up table' (LUT). This effect is also called Color Grading.
  78111. //
  78112. // The object needs to be provided an url to a texture containing the color
  78113. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  78114. // Use an image editing software to tweak the LUT to match your needs.
  78115. //
  78116. // For an example of a color LUT, see here:
  78117. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  78118. // For explanations on color grading, see here:
  78119. // http://udn.epicgames.com/Three/ColorGrading.html
  78120. //
  78121. var BABYLON;
  78122. (function (BABYLON) {
  78123. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  78124. __extends(ColorCorrectionPostProcess, _super);
  78125. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  78126. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  78127. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78128. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  78129. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78130. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78131. _this.onApply = function (effect) {
  78132. effect.setTexture("colorTable", _this._colorTableTexture);
  78133. };
  78134. return _this;
  78135. }
  78136. return ColorCorrectionPostProcess;
  78137. }(BABYLON.PostProcess));
  78138. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  78139. })(BABYLON || (BABYLON = {}));
  78140. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  78141. var BABYLON;
  78142. (function (BABYLON) {
  78143. /** Defines operator used for tonemapping */
  78144. var TonemappingOperator;
  78145. (function (TonemappingOperator) {
  78146. /** Hable */
  78147. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  78148. /** Reinhard */
  78149. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  78150. /** HejiDawson */
  78151. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  78152. /** Photographic */
  78153. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  78154. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  78155. ;
  78156. /**
  78157. * Defines a post process to apply tone mapping
  78158. */
  78159. var TonemapPostProcess = /** @class */ (function (_super) {
  78160. __extends(TonemapPostProcess, _super);
  78161. /**
  78162. * Creates a new TonemapPostProcess
  78163. * @param name defines the name of the postprocess
  78164. * @param _operator defines the operator to use
  78165. * @param exposureAdjustment defines the required exposure adjustement
  78166. * @param camera defines the camera to use (can be null)
  78167. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  78168. * @param engine defines the hosting engine (can be ignore if camera is set)
  78169. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  78170. */
  78171. function TonemapPostProcess(name, _operator,
  78172. /** Defines the required exposure adjustement */
  78173. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  78174. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78175. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78176. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  78177. _this._operator = _operator;
  78178. _this.exposureAdjustment = exposureAdjustment;
  78179. var defines = "#define ";
  78180. if (_this._operator === TonemappingOperator.Hable)
  78181. defines += "HABLE_TONEMAPPING";
  78182. else if (_this._operator === TonemappingOperator.Reinhard)
  78183. defines += "REINHARD_TONEMAPPING";
  78184. else if (_this._operator === TonemappingOperator.HejiDawson)
  78185. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  78186. else if (_this._operator === TonemappingOperator.Photographic)
  78187. defines += "PHOTOGRAPHIC_TONEMAPPING";
  78188. //sadly a second call to create the effect.
  78189. _this.updateEffect(defines);
  78190. _this.onApply = function (effect) {
  78191. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  78192. };
  78193. return _this;
  78194. }
  78195. return TonemapPostProcess;
  78196. }(BABYLON.PostProcess));
  78197. BABYLON.TonemapPostProcess = TonemapPostProcess;
  78198. })(BABYLON || (BABYLON = {}));
  78199. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  78200. var BABYLON;
  78201. (function (BABYLON) {
  78202. var DisplayPassPostProcess = /** @class */ (function (_super) {
  78203. __extends(DisplayPassPostProcess, _super);
  78204. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  78205. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  78206. }
  78207. return DisplayPassPostProcess;
  78208. }(BABYLON.PostProcess));
  78209. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  78210. })(BABYLON || (BABYLON = {}));
  78211. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  78212. var BABYLON;
  78213. (function (BABYLON) {
  78214. var HighlightsPostProcess = /** @class */ (function (_super) {
  78215. __extends(HighlightsPostProcess, _super);
  78216. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  78217. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78218. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  78219. }
  78220. return HighlightsPostProcess;
  78221. }(BABYLON.PostProcess));
  78222. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  78223. })(BABYLON || (BABYLON = {}));
  78224. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  78225. var BABYLON;
  78226. (function (BABYLON) {
  78227. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  78228. __extends(ImageProcessingPostProcess, _super);
  78229. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  78230. if (camera === void 0) { camera = null; }
  78231. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78232. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  78233. _this._fromLinearSpace = true;
  78234. /**
  78235. * Defines cache preventing GC.
  78236. */
  78237. _this._defines = {
  78238. IMAGEPROCESSING: false,
  78239. VIGNETTE: false,
  78240. VIGNETTEBLENDMODEMULTIPLY: false,
  78241. VIGNETTEBLENDMODEOPAQUE: false,
  78242. TONEMAPPING: false,
  78243. CONTRAST: false,
  78244. COLORCURVES: false,
  78245. COLORGRADING: false,
  78246. COLORGRADING3D: false,
  78247. FROMLINEARSPACE: false,
  78248. SAMPLER3DGREENDEPTH: false,
  78249. SAMPLER3DBGRMAP: false,
  78250. IMAGEPROCESSINGPOSTPROCESS: false,
  78251. EXPOSURE: false,
  78252. };
  78253. // Setup the configuration as forced by the constructor. This would then not force the
  78254. // scene materials output in linear space and let untouched the default forward pass.
  78255. if (imageProcessingConfiguration) {
  78256. imageProcessingConfiguration.applyByPostProcess = true;
  78257. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  78258. // This will cause the shader to be compiled
  78259. _this.fromLinearSpace = false;
  78260. }
  78261. // Setup the default processing configuration to the scene.
  78262. else {
  78263. _this._attachImageProcessingConfiguration(null, true);
  78264. _this.imageProcessingConfiguration.applyByPostProcess = true;
  78265. }
  78266. _this.onApply = function (effect) {
  78267. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  78268. };
  78269. return _this;
  78270. }
  78271. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  78272. /**
  78273. * Gets the image processing configuration used either in this material.
  78274. */
  78275. get: function () {
  78276. return this._imageProcessingConfiguration;
  78277. },
  78278. /**
  78279. * Sets the Default image processing configuration used either in the this material.
  78280. *
  78281. * If sets to null, the scene one is in use.
  78282. */
  78283. set: function (value) {
  78284. this._attachImageProcessingConfiguration(value);
  78285. },
  78286. enumerable: true,
  78287. configurable: true
  78288. });
  78289. /**
  78290. * Attaches a new image processing configuration to the PBR Material.
  78291. * @param configuration
  78292. */
  78293. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  78294. var _this = this;
  78295. if (doNotBuild === void 0) { doNotBuild = false; }
  78296. if (configuration === this._imageProcessingConfiguration) {
  78297. return;
  78298. }
  78299. // Detaches observer.
  78300. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78301. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78302. }
  78303. // Pick the scene configuration if needed.
  78304. if (!configuration) {
  78305. var scene = null;
  78306. var engine = this.getEngine();
  78307. var camera = this.getCamera();
  78308. if (camera) {
  78309. scene = camera.getScene();
  78310. }
  78311. else if (engine && engine.scenes) {
  78312. var scenes = engine.scenes;
  78313. scene = scenes[scenes.length - 1];
  78314. }
  78315. else {
  78316. scene = BABYLON.Engine.LastCreatedScene;
  78317. }
  78318. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  78319. }
  78320. else {
  78321. this._imageProcessingConfiguration = configuration;
  78322. }
  78323. // Attaches observer.
  78324. if (this._imageProcessingConfiguration) {
  78325. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  78326. _this._updateParameters();
  78327. });
  78328. }
  78329. // Ensure the effect will be rebuilt.
  78330. if (!doNotBuild) {
  78331. this._updateParameters();
  78332. }
  78333. };
  78334. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  78335. /**
  78336. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  78337. */
  78338. get: function () {
  78339. return this.imageProcessingConfiguration.colorCurves;
  78340. },
  78341. /**
  78342. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  78343. */
  78344. set: function (value) {
  78345. this.imageProcessingConfiguration.colorCurves = value;
  78346. },
  78347. enumerable: true,
  78348. configurable: true
  78349. });
  78350. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  78351. /**
  78352. * Gets wether the color curves effect is enabled.
  78353. */
  78354. get: function () {
  78355. return this.imageProcessingConfiguration.colorCurvesEnabled;
  78356. },
  78357. /**
  78358. * Sets wether the color curves effect is enabled.
  78359. */
  78360. set: function (value) {
  78361. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  78362. },
  78363. enumerable: true,
  78364. configurable: true
  78365. });
  78366. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  78367. /**
  78368. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  78369. */
  78370. get: function () {
  78371. return this.imageProcessingConfiguration.colorGradingTexture;
  78372. },
  78373. /**
  78374. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  78375. */
  78376. set: function (value) {
  78377. this.imageProcessingConfiguration.colorGradingTexture = value;
  78378. },
  78379. enumerable: true,
  78380. configurable: true
  78381. });
  78382. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  78383. /**
  78384. * Gets wether the color grading effect is enabled.
  78385. */
  78386. get: function () {
  78387. return this.imageProcessingConfiguration.colorGradingEnabled;
  78388. },
  78389. /**
  78390. * Gets wether the color grading effect is enabled.
  78391. */
  78392. set: function (value) {
  78393. this.imageProcessingConfiguration.colorGradingEnabled = value;
  78394. },
  78395. enumerable: true,
  78396. configurable: true
  78397. });
  78398. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  78399. /**
  78400. * Gets exposure used in the effect.
  78401. */
  78402. get: function () {
  78403. return this.imageProcessingConfiguration.exposure;
  78404. },
  78405. /**
  78406. * Sets exposure used in the effect.
  78407. */
  78408. set: function (value) {
  78409. this.imageProcessingConfiguration.exposure = value;
  78410. },
  78411. enumerable: true,
  78412. configurable: true
  78413. });
  78414. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  78415. /**
  78416. * Gets wether tonemapping is enabled or not.
  78417. */
  78418. get: function () {
  78419. return this._imageProcessingConfiguration.toneMappingEnabled;
  78420. },
  78421. /**
  78422. * Sets wether tonemapping is enabled or not
  78423. */
  78424. set: function (value) {
  78425. this._imageProcessingConfiguration.toneMappingEnabled = value;
  78426. },
  78427. enumerable: true,
  78428. configurable: true
  78429. });
  78430. ;
  78431. ;
  78432. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  78433. /**
  78434. * Gets contrast used in the effect.
  78435. */
  78436. get: function () {
  78437. return this.imageProcessingConfiguration.contrast;
  78438. },
  78439. /**
  78440. * Sets contrast used in the effect.
  78441. */
  78442. set: function (value) {
  78443. this.imageProcessingConfiguration.contrast = value;
  78444. },
  78445. enumerable: true,
  78446. configurable: true
  78447. });
  78448. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  78449. /**
  78450. * Gets Vignette stretch size.
  78451. */
  78452. get: function () {
  78453. return this.imageProcessingConfiguration.vignetteStretch;
  78454. },
  78455. /**
  78456. * Sets Vignette stretch size.
  78457. */
  78458. set: function (value) {
  78459. this.imageProcessingConfiguration.vignetteStretch = value;
  78460. },
  78461. enumerable: true,
  78462. configurable: true
  78463. });
  78464. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  78465. /**
  78466. * Gets Vignette centre X Offset.
  78467. */
  78468. get: function () {
  78469. return this.imageProcessingConfiguration.vignetteCentreX;
  78470. },
  78471. /**
  78472. * Sets Vignette centre X Offset.
  78473. */
  78474. set: function (value) {
  78475. this.imageProcessingConfiguration.vignetteCentreX = value;
  78476. },
  78477. enumerable: true,
  78478. configurable: true
  78479. });
  78480. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  78481. /**
  78482. * Gets Vignette centre Y Offset.
  78483. */
  78484. get: function () {
  78485. return this.imageProcessingConfiguration.vignetteCentreY;
  78486. },
  78487. /**
  78488. * Sets Vignette centre Y Offset.
  78489. */
  78490. set: function (value) {
  78491. this.imageProcessingConfiguration.vignetteCentreY = value;
  78492. },
  78493. enumerable: true,
  78494. configurable: true
  78495. });
  78496. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  78497. /**
  78498. * Gets Vignette weight or intensity of the vignette effect.
  78499. */
  78500. get: function () {
  78501. return this.imageProcessingConfiguration.vignetteWeight;
  78502. },
  78503. /**
  78504. * Sets Vignette weight or intensity of the vignette effect.
  78505. */
  78506. set: function (value) {
  78507. this.imageProcessingConfiguration.vignetteWeight = value;
  78508. },
  78509. enumerable: true,
  78510. configurable: true
  78511. });
  78512. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  78513. /**
  78514. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78515. * if vignetteEnabled is set to true.
  78516. */
  78517. get: function () {
  78518. return this.imageProcessingConfiguration.vignetteColor;
  78519. },
  78520. /**
  78521. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78522. * if vignetteEnabled is set to true.
  78523. */
  78524. set: function (value) {
  78525. this.imageProcessingConfiguration.vignetteColor = value;
  78526. },
  78527. enumerable: true,
  78528. configurable: true
  78529. });
  78530. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  78531. /**
  78532. * Gets Camera field of view used by the Vignette effect.
  78533. */
  78534. get: function () {
  78535. return this.imageProcessingConfiguration.vignetteCameraFov;
  78536. },
  78537. /**
  78538. * Sets Camera field of view used by the Vignette effect.
  78539. */
  78540. set: function (value) {
  78541. this.imageProcessingConfiguration.vignetteCameraFov = value;
  78542. },
  78543. enumerable: true,
  78544. configurable: true
  78545. });
  78546. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  78547. /**
  78548. * Gets the vignette blend mode allowing different kind of effect.
  78549. */
  78550. get: function () {
  78551. return this.imageProcessingConfiguration.vignetteBlendMode;
  78552. },
  78553. /**
  78554. * Sets the vignette blend mode allowing different kind of effect.
  78555. */
  78556. set: function (value) {
  78557. this.imageProcessingConfiguration.vignetteBlendMode = value;
  78558. },
  78559. enumerable: true,
  78560. configurable: true
  78561. });
  78562. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  78563. /**
  78564. * Gets wether the vignette effect is enabled.
  78565. */
  78566. get: function () {
  78567. return this.imageProcessingConfiguration.vignetteEnabled;
  78568. },
  78569. /**
  78570. * Sets wether the vignette effect is enabled.
  78571. */
  78572. set: function (value) {
  78573. this.imageProcessingConfiguration.vignetteEnabled = value;
  78574. },
  78575. enumerable: true,
  78576. configurable: true
  78577. });
  78578. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  78579. /**
  78580. * Gets wether the input of the processing is in Gamma or Linear Space.
  78581. */
  78582. get: function () {
  78583. return this._fromLinearSpace;
  78584. },
  78585. /**
  78586. * Sets wether the input of the processing is in Gamma or Linear Space.
  78587. */
  78588. set: function (value) {
  78589. if (this._fromLinearSpace === value) {
  78590. return;
  78591. }
  78592. this._fromLinearSpace = value;
  78593. this._updateParameters();
  78594. },
  78595. enumerable: true,
  78596. configurable: true
  78597. });
  78598. ImageProcessingPostProcess.prototype.getClassName = function () {
  78599. return "ImageProcessingPostProcess";
  78600. };
  78601. ImageProcessingPostProcess.prototype._updateParameters = function () {
  78602. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  78603. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  78604. var defines = "";
  78605. for (var define in this._defines) {
  78606. if (this._defines[define]) {
  78607. defines += "#define " + define + ";\r\n";
  78608. }
  78609. }
  78610. var samplers = ["textureSampler"];
  78611. var uniforms = ["scale"];
  78612. if (BABYLON.ImageProcessingConfiguration) {
  78613. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  78614. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  78615. }
  78616. this.updateEffect(defines, uniforms, samplers);
  78617. };
  78618. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  78619. _super.prototype.dispose.call(this, camera);
  78620. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78621. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78622. }
  78623. if (this._imageProcessingConfiguration) {
  78624. this.imageProcessingConfiguration.applyByPostProcess = false;
  78625. }
  78626. };
  78627. __decorate([
  78628. BABYLON.serialize()
  78629. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  78630. return ImageProcessingPostProcess;
  78631. }(BABYLON.PostProcess));
  78632. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  78633. })(BABYLON || (BABYLON = {}));
  78634. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  78635. var BABYLON;
  78636. (function (BABYLON) {
  78637. /**
  78638. * Class used to store bone information
  78639. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  78640. */
  78641. var Bone = /** @class */ (function (_super) {
  78642. __extends(Bone, _super);
  78643. /**
  78644. * Create a new bone
  78645. * @param name defines the bone name
  78646. * @param skeleton defines the parent skeleton
  78647. * @param parentBone defines the parent (can be null if the bone is the root)
  78648. * @param localMatrix defines the local matrix
  78649. * @param restPose defines the rest pose matrix
  78650. * @param baseMatrix defines the base matrix
  78651. * @param index defines index of the bone in the hiearchy
  78652. */
  78653. function Bone(
  78654. /**
  78655. * defines the bone name
  78656. */
  78657. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  78658. if (parentBone === void 0) { parentBone = null; }
  78659. if (localMatrix === void 0) { localMatrix = null; }
  78660. if (restPose === void 0) { restPose = null; }
  78661. if (baseMatrix === void 0) { baseMatrix = null; }
  78662. if (index === void 0) { index = null; }
  78663. var _this = _super.call(this, name, skeleton.getScene()) || this;
  78664. _this.name = name;
  78665. /**
  78666. * Gets the list of child bones
  78667. */
  78668. _this.children = new Array();
  78669. /** Gets the animations associated with this bone */
  78670. _this.animations = new Array();
  78671. /**
  78672. * @hidden Internal only
  78673. * Set this value to map this bone to a different index in the transform matrices
  78674. * Set this value to -1 to exclude the bone from the transform matrices
  78675. */
  78676. _this._index = null;
  78677. _this._absoluteTransform = new BABYLON.Matrix();
  78678. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  78679. _this._scalingDeterminant = 1;
  78680. _this._worldTransform = new BABYLON.Matrix();
  78681. _this._needToDecompose = true;
  78682. _this._needToCompose = false;
  78683. _this._skeleton = skeleton;
  78684. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  78685. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  78686. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  78687. _this._index = index;
  78688. skeleton.bones.push(_this);
  78689. _this.setParent(parentBone, false);
  78690. if (baseMatrix || localMatrix) {
  78691. _this._updateDifferenceMatrix();
  78692. }
  78693. return _this;
  78694. }
  78695. Object.defineProperty(Bone.prototype, "_matrix", {
  78696. /** @hidden */
  78697. get: function () {
  78698. this._compose();
  78699. return this._localMatrix;
  78700. },
  78701. /** @hidden */
  78702. set: function (value) {
  78703. this._localMatrix.copyFrom(value);
  78704. this._needToDecompose = true;
  78705. },
  78706. enumerable: true,
  78707. configurable: true
  78708. });
  78709. // Members
  78710. /**
  78711. * Gets the parent skeleton
  78712. * @returns a skeleton
  78713. */
  78714. Bone.prototype.getSkeleton = function () {
  78715. return this._skeleton;
  78716. };
  78717. /**
  78718. * Gets parent bone
  78719. * @returns a bone or null if the bone is the root of the bone hierarchy
  78720. */
  78721. Bone.prototype.getParent = function () {
  78722. return this._parent;
  78723. };
  78724. /**
  78725. * Sets the parent bone
  78726. * @param parent defines the parent (can be null if the bone is the root)
  78727. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78728. */
  78729. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  78730. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78731. if (this._parent === parent) {
  78732. return;
  78733. }
  78734. if (this._parent) {
  78735. var index = this._parent.children.indexOf(this);
  78736. if (index !== -1) {
  78737. this._parent.children.splice(index, 1);
  78738. }
  78739. }
  78740. this._parent = parent;
  78741. if (this._parent) {
  78742. this._parent.children.push(this);
  78743. }
  78744. if (updateDifferenceMatrix) {
  78745. this._updateDifferenceMatrix();
  78746. }
  78747. this.markAsDirty();
  78748. };
  78749. /**
  78750. * Gets the local matrix
  78751. * @returns a matrix
  78752. */
  78753. Bone.prototype.getLocalMatrix = function () {
  78754. this._compose();
  78755. return this._localMatrix;
  78756. };
  78757. /**
  78758. * Gets the base matrix (initial matrix which remains unchanged)
  78759. * @returns a matrix
  78760. */
  78761. Bone.prototype.getBaseMatrix = function () {
  78762. return this._baseMatrix;
  78763. };
  78764. /**
  78765. * Gets the rest pose matrix
  78766. * @returns a matrix
  78767. */
  78768. Bone.prototype.getRestPose = function () {
  78769. return this._restPose;
  78770. };
  78771. /**
  78772. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  78773. */
  78774. Bone.prototype.getWorldMatrix = function () {
  78775. return this._worldTransform;
  78776. };
  78777. /**
  78778. * Sets the local matrix to rest pose matrix
  78779. */
  78780. Bone.prototype.returnToRest = function () {
  78781. this.updateMatrix(this._restPose.clone());
  78782. };
  78783. /**
  78784. * Gets the inverse of the absolute transform matrix.
  78785. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  78786. * @returns a matrix
  78787. */
  78788. Bone.prototype.getInvertedAbsoluteTransform = function () {
  78789. return this._invertedAbsoluteTransform;
  78790. };
  78791. /**
  78792. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  78793. * @returns a matrix
  78794. */
  78795. Bone.prototype.getAbsoluteTransform = function () {
  78796. return this._absoluteTransform;
  78797. };
  78798. Object.defineProperty(Bone.prototype, "position", {
  78799. // Properties (matches AbstractMesh properties)
  78800. /** Gets or sets current position (in local space) */
  78801. get: function () {
  78802. this._decompose();
  78803. return this._localPosition;
  78804. },
  78805. set: function (newPosition) {
  78806. this._decompose();
  78807. this._localPosition.copyFrom(newPosition);
  78808. this._markAsDirtyAndCompose();
  78809. },
  78810. enumerable: true,
  78811. configurable: true
  78812. });
  78813. Object.defineProperty(Bone.prototype, "rotation", {
  78814. /** Gets or sets current rotation (in local space) */
  78815. get: function () {
  78816. return this.getRotation();
  78817. },
  78818. set: function (newRotation) {
  78819. this.setRotation(newRotation);
  78820. },
  78821. enumerable: true,
  78822. configurable: true
  78823. });
  78824. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  78825. /** Gets or sets current rotation quaternion (in local space) */
  78826. get: function () {
  78827. this._decompose();
  78828. return this._localRotation;
  78829. },
  78830. set: function (newRotation) {
  78831. this.setRotationQuaternion(newRotation);
  78832. },
  78833. enumerable: true,
  78834. configurable: true
  78835. });
  78836. Object.defineProperty(Bone.prototype, "scaling", {
  78837. /** Gets or sets current scaling (in local space) */
  78838. get: function () {
  78839. return this.getScale();
  78840. },
  78841. set: function (newScaling) {
  78842. this.setScale(newScaling);
  78843. },
  78844. enumerable: true,
  78845. configurable: true
  78846. });
  78847. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  78848. /**
  78849. * Gets the animation properties override
  78850. */
  78851. get: function () {
  78852. return this._skeleton.animationPropertiesOverride;
  78853. },
  78854. enumerable: true,
  78855. configurable: true
  78856. });
  78857. // Methods
  78858. Bone.prototype._decompose = function () {
  78859. if (!this._needToDecompose) {
  78860. return;
  78861. }
  78862. this._needToDecompose = false;
  78863. if (!this._localScaling) {
  78864. this._localScaling = BABYLON.Vector3.Zero();
  78865. this._localRotation = BABYLON.Quaternion.Zero();
  78866. this._localPosition = BABYLON.Vector3.Zero();
  78867. }
  78868. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  78869. };
  78870. Bone.prototype._compose = function () {
  78871. if (!this._needToCompose) {
  78872. return;
  78873. }
  78874. this._needToCompose = false;
  78875. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  78876. };
  78877. /**
  78878. * Update the base and local matrices
  78879. * @param matrix defines the new base or local matrix
  78880. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78881. * @param updateLocalMatrix defines if the local matrix should be updated
  78882. */
  78883. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  78884. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78885. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  78886. this._baseMatrix.copyFrom(matrix);
  78887. if (updateDifferenceMatrix) {
  78888. this._updateDifferenceMatrix();
  78889. }
  78890. if (updateLocalMatrix) {
  78891. this._localMatrix.copyFrom(matrix);
  78892. this._markAsDirtyAndDecompose();
  78893. }
  78894. else {
  78895. this.markAsDirty();
  78896. }
  78897. };
  78898. /** @hidden */
  78899. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  78900. if (updateChildren === void 0) { updateChildren = true; }
  78901. if (!rootMatrix) {
  78902. rootMatrix = this._baseMatrix;
  78903. }
  78904. if (this._parent) {
  78905. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78906. }
  78907. else {
  78908. this._absoluteTransform.copyFrom(rootMatrix);
  78909. }
  78910. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  78911. if (updateChildren) {
  78912. for (var index = 0; index < this.children.length; index++) {
  78913. this.children[index]._updateDifferenceMatrix();
  78914. }
  78915. }
  78916. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  78917. };
  78918. /**
  78919. * Flag the bone as dirty (Forcing it to update everything)
  78920. */
  78921. Bone.prototype.markAsDirty = function () {
  78922. this._currentRenderId++;
  78923. this._childRenderId++;
  78924. this._skeleton._markAsDirty();
  78925. };
  78926. Bone.prototype._markAsDirtyAndCompose = function () {
  78927. this.markAsDirty();
  78928. this._needToCompose = true;
  78929. };
  78930. Bone.prototype._markAsDirtyAndDecompose = function () {
  78931. this.markAsDirty();
  78932. this._needToDecompose = true;
  78933. };
  78934. /**
  78935. * Copy an animation range from another bone
  78936. * @param source defines the source bone
  78937. * @param rangeName defines the range name to copy
  78938. * @param frameOffset defines the frame offset
  78939. * @param rescaleAsRequired defines if rescaling must be applied if required
  78940. * @param skelDimensionsRatio defines the scaling ratio
  78941. * @returns true if operation was successful
  78942. */
  78943. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  78944. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  78945. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  78946. // all animation may be coming from a library skeleton, so may need to create animation
  78947. if (this.animations.length === 0) {
  78948. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  78949. this.animations[0].setKeys([]);
  78950. }
  78951. // get animation info / verify there is such a range from the source bone
  78952. var sourceRange = source.animations[0].getRange(rangeName);
  78953. if (!sourceRange) {
  78954. return false;
  78955. }
  78956. var from = sourceRange.from;
  78957. var to = sourceRange.to;
  78958. var sourceKeys = source.animations[0].getKeys();
  78959. // rescaling prep
  78960. var sourceBoneLength = source.length;
  78961. var sourceParent = source.getParent();
  78962. var parent = this.getParent();
  78963. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  78964. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  78965. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  78966. var destKeys = this.animations[0].getKeys();
  78967. // loop vars declaration
  78968. var orig;
  78969. var origTranslation;
  78970. var mat;
  78971. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  78972. orig = sourceKeys[key];
  78973. if (orig.frame >= from && orig.frame <= to) {
  78974. if (rescaleAsRequired) {
  78975. mat = orig.value.clone();
  78976. // scale based on parent ratio, when bone has parent
  78977. if (parentScalingReqd) {
  78978. origTranslation = mat.getTranslation();
  78979. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  78980. // scale based on skeleton dimension ratio when root bone, and value is passed
  78981. }
  78982. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  78983. origTranslation = mat.getTranslation();
  78984. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  78985. // use original when root bone, and no data for skelDimensionsRatio
  78986. }
  78987. else {
  78988. mat = orig.value;
  78989. }
  78990. }
  78991. else {
  78992. mat = orig.value;
  78993. }
  78994. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  78995. }
  78996. }
  78997. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  78998. return true;
  78999. };
  79000. /**
  79001. * Translate the bone in local or world space
  79002. * @param vec The amount to translate the bone
  79003. * @param space The space that the translation is in
  79004. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79005. */
  79006. Bone.prototype.translate = function (vec, space, mesh) {
  79007. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79008. var lm = this.getLocalMatrix();
  79009. if (space == BABYLON.Space.LOCAL) {
  79010. lm.m[12] += vec.x;
  79011. lm.m[13] += vec.y;
  79012. lm.m[14] += vec.z;
  79013. }
  79014. else {
  79015. var wm = null;
  79016. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79017. if (mesh) {
  79018. wm = mesh.getWorldMatrix();
  79019. }
  79020. this._skeleton.computeAbsoluteTransforms();
  79021. var tmat = Bone._tmpMats[0];
  79022. var tvec = Bone._tmpVecs[0];
  79023. if (this._parent) {
  79024. if (mesh && wm) {
  79025. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79026. tmat.multiplyToRef(wm, tmat);
  79027. }
  79028. else {
  79029. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79030. }
  79031. }
  79032. tmat.m[12] = 0;
  79033. tmat.m[13] = 0;
  79034. tmat.m[14] = 0;
  79035. tmat.invert();
  79036. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  79037. lm.m[12] += tvec.x;
  79038. lm.m[13] += tvec.y;
  79039. lm.m[14] += tvec.z;
  79040. }
  79041. this._markAsDirtyAndDecompose();
  79042. };
  79043. /**
  79044. * Set the postion of the bone in local or world space
  79045. * @param position The position to set the bone
  79046. * @param space The space that the position is in
  79047. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79048. */
  79049. Bone.prototype.setPosition = function (position, space, mesh) {
  79050. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79051. var lm = this.getLocalMatrix();
  79052. if (space == BABYLON.Space.LOCAL) {
  79053. lm.m[12] = position.x;
  79054. lm.m[13] = position.y;
  79055. lm.m[14] = position.z;
  79056. }
  79057. else {
  79058. var wm = null;
  79059. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79060. if (mesh) {
  79061. wm = mesh.getWorldMatrix();
  79062. }
  79063. this._skeleton.computeAbsoluteTransforms();
  79064. var tmat = Bone._tmpMats[0];
  79065. var vec = Bone._tmpVecs[0];
  79066. if (this._parent) {
  79067. if (mesh && wm) {
  79068. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79069. tmat.multiplyToRef(wm, tmat);
  79070. }
  79071. else {
  79072. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79073. }
  79074. }
  79075. tmat.invert();
  79076. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  79077. lm.m[12] = vec.x;
  79078. lm.m[13] = vec.y;
  79079. lm.m[14] = vec.z;
  79080. }
  79081. this._markAsDirtyAndDecompose();
  79082. };
  79083. /**
  79084. * Set the absolute position of the bone (world space)
  79085. * @param position The position to set the bone
  79086. * @param mesh The mesh that this bone is attached to
  79087. */
  79088. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  79089. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  79090. };
  79091. /**
  79092. * Scale the bone on the x, y and z axes (in local space)
  79093. * @param x The amount to scale the bone on the x axis
  79094. * @param y The amount to scale the bone on the y axis
  79095. * @param z The amount to scale the bone on the z axis
  79096. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  79097. */
  79098. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  79099. if (scaleChildren === void 0) { scaleChildren = false; }
  79100. var locMat = this.getLocalMatrix();
  79101. // Apply new scaling on top of current local matrix
  79102. var scaleMat = Bone._tmpMats[0];
  79103. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  79104. scaleMat.multiplyToRef(locMat, locMat);
  79105. // Invert scaling matrix and apply the inverse to all children
  79106. scaleMat.invert();
  79107. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  79108. var child = _a[_i];
  79109. var cm = child.getLocalMatrix();
  79110. cm.multiplyToRef(scaleMat, cm);
  79111. cm.m[12] *= x;
  79112. cm.m[13] *= y;
  79113. cm.m[14] *= z;
  79114. child._markAsDirtyAndDecompose();
  79115. }
  79116. this._markAsDirtyAndDecompose();
  79117. if (scaleChildren) {
  79118. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  79119. var child = _c[_b];
  79120. child.scale(x, y, z, scaleChildren);
  79121. }
  79122. }
  79123. };
  79124. /**
  79125. * Set the bone scaling in local space
  79126. * @param scale defines the scaling vector
  79127. */
  79128. Bone.prototype.setScale = function (scale) {
  79129. this._decompose();
  79130. this._localScaling.copyFrom(scale);
  79131. this._markAsDirtyAndCompose();
  79132. };
  79133. /**
  79134. * Gets the current scaling in local space
  79135. * @returns the current scaling vector
  79136. */
  79137. Bone.prototype.getScale = function () {
  79138. this._decompose();
  79139. return this._localScaling;
  79140. };
  79141. /**
  79142. * Gets the current scaling in local space and stores it in a target vector
  79143. * @param result defines the target vector
  79144. */
  79145. Bone.prototype.getScaleToRef = function (result) {
  79146. this._decompose();
  79147. result.copyFrom(this._localScaling);
  79148. };
  79149. /**
  79150. * Set the yaw, pitch, and roll of the bone in local or world space
  79151. * @param yaw The rotation of the bone on the y axis
  79152. * @param pitch The rotation of the bone on the x axis
  79153. * @param roll The rotation of the bone on the z axis
  79154. * @param space The space that the axes of rotation are in
  79155. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79156. */
  79157. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  79158. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79159. if (space === BABYLON.Space.LOCAL) {
  79160. var quat = Bone._tmpQuat;
  79161. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  79162. this.setRotationQuaternion(quat, space, mesh);
  79163. return;
  79164. }
  79165. var rotMatInv = Bone._tmpMats[0];
  79166. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79167. return;
  79168. }
  79169. var rotMat = Bone._tmpMats[1];
  79170. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  79171. rotMatInv.multiplyToRef(rotMat, rotMat);
  79172. this._rotateWithMatrix(rotMat, space, mesh);
  79173. };
  79174. /**
  79175. * Add a rotation to the bone on an axis in local or world space
  79176. * @param axis The axis to rotate the bone on
  79177. * @param amount The amount to rotate the bone
  79178. * @param space The space that the axis is in
  79179. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79180. */
  79181. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  79182. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79183. var rmat = Bone._tmpMats[0];
  79184. rmat.m[12] = 0;
  79185. rmat.m[13] = 0;
  79186. rmat.m[14] = 0;
  79187. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  79188. this._rotateWithMatrix(rmat, space, mesh);
  79189. };
  79190. /**
  79191. * Set the rotation of the bone to a particular axis angle in local or world space
  79192. * @param axis The axis to rotate the bone on
  79193. * @param angle The angle that the bone should be rotated to
  79194. * @param space The space that the axis is in
  79195. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79196. */
  79197. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  79198. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79199. if (space === BABYLON.Space.LOCAL) {
  79200. var quat = Bone._tmpQuat;
  79201. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  79202. this.setRotationQuaternion(quat, space, mesh);
  79203. return;
  79204. }
  79205. var rotMatInv = Bone._tmpMats[0];
  79206. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79207. return;
  79208. }
  79209. var rotMat = Bone._tmpMats[1];
  79210. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  79211. rotMatInv.multiplyToRef(rotMat, rotMat);
  79212. this._rotateWithMatrix(rotMat, space, mesh);
  79213. };
  79214. /**
  79215. * Set the euler rotation of the bone in local of world space
  79216. * @param rotation The euler rotation that the bone should be set to
  79217. * @param space The space that the rotation is in
  79218. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79219. */
  79220. Bone.prototype.setRotation = function (rotation, space, mesh) {
  79221. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79222. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  79223. };
  79224. /**
  79225. * Set the quaternion rotation of the bone in local of world space
  79226. * @param quat The quaternion rotation that the bone should be set to
  79227. * @param space The space that the rotation is in
  79228. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79229. */
  79230. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  79231. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79232. if (space === BABYLON.Space.LOCAL) {
  79233. this._decompose();
  79234. this._localRotation.copyFrom(quat);
  79235. this._markAsDirtyAndCompose();
  79236. return;
  79237. }
  79238. var rotMatInv = Bone._tmpMats[0];
  79239. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79240. return;
  79241. }
  79242. var rotMat = Bone._tmpMats[1];
  79243. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  79244. rotMatInv.multiplyToRef(rotMat, rotMat);
  79245. this._rotateWithMatrix(rotMat, space, mesh);
  79246. };
  79247. /**
  79248. * Set the rotation matrix of the bone in local of world space
  79249. * @param rotMat The rotation matrix that the bone should be set to
  79250. * @param space The space that the rotation is in
  79251. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79252. */
  79253. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  79254. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79255. if (space === BABYLON.Space.LOCAL) {
  79256. var quat = Bone._tmpQuat;
  79257. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  79258. this.setRotationQuaternion(quat, space, mesh);
  79259. return;
  79260. }
  79261. var rotMatInv = Bone._tmpMats[0];
  79262. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79263. return;
  79264. }
  79265. var rotMat2 = Bone._tmpMats[1];
  79266. rotMat2.copyFrom(rotMat);
  79267. rotMatInv.multiplyToRef(rotMat, rotMat2);
  79268. this._rotateWithMatrix(rotMat2, space, mesh);
  79269. };
  79270. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  79271. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79272. var lmat = this.getLocalMatrix();
  79273. var lx = lmat.m[12];
  79274. var ly = lmat.m[13];
  79275. var lz = lmat.m[14];
  79276. var parent = this.getParent();
  79277. var parentScale = Bone._tmpMats[3];
  79278. var parentScaleInv = Bone._tmpMats[4];
  79279. if (parent && space == BABYLON.Space.WORLD) {
  79280. if (mesh) {
  79281. parentScale.copyFrom(mesh.getWorldMatrix());
  79282. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  79283. }
  79284. else {
  79285. parentScale.copyFrom(parent.getAbsoluteTransform());
  79286. }
  79287. parentScaleInv.copyFrom(parentScale);
  79288. parentScaleInv.invert();
  79289. lmat.multiplyToRef(parentScale, lmat);
  79290. lmat.multiplyToRef(rmat, lmat);
  79291. lmat.multiplyToRef(parentScaleInv, lmat);
  79292. }
  79293. else {
  79294. if (space == BABYLON.Space.WORLD && mesh) {
  79295. parentScale.copyFrom(mesh.getWorldMatrix());
  79296. parentScaleInv.copyFrom(parentScale);
  79297. parentScaleInv.invert();
  79298. lmat.multiplyToRef(parentScale, lmat);
  79299. lmat.multiplyToRef(rmat, lmat);
  79300. lmat.multiplyToRef(parentScaleInv, lmat);
  79301. }
  79302. else {
  79303. lmat.multiplyToRef(rmat, lmat);
  79304. }
  79305. }
  79306. lmat.m[12] = lx;
  79307. lmat.m[13] = ly;
  79308. lmat.m[14] = lz;
  79309. this.computeAbsoluteTransforms();
  79310. this._markAsDirtyAndDecompose();
  79311. };
  79312. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  79313. var scaleMatrix = Bone._tmpMats[2];
  79314. rotMatInv.copyFrom(this.getAbsoluteTransform());
  79315. if (mesh) {
  79316. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  79317. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  79318. }
  79319. rotMatInv.invert();
  79320. if (isNaN(rotMatInv.m[0])) {
  79321. // Matrix failed to invert.
  79322. // This can happen if scale is zero for example.
  79323. return false;
  79324. }
  79325. scaleMatrix.m[0] *= this._scalingDeterminant;
  79326. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  79327. return true;
  79328. };
  79329. /**
  79330. * Get the position of the bone in local or world space
  79331. * @param space The space that the returned position is in
  79332. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79333. * @returns The position of the bone
  79334. */
  79335. Bone.prototype.getPosition = function (space, mesh) {
  79336. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79337. if (mesh === void 0) { mesh = null; }
  79338. var pos = BABYLON.Vector3.Zero();
  79339. this.getPositionToRef(space, mesh, pos);
  79340. return pos;
  79341. };
  79342. /**
  79343. * Copy the position of the bone to a vector3 in local or world space
  79344. * @param space The space that the returned position is in
  79345. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79346. * @param result The vector3 to copy the position to
  79347. */
  79348. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  79349. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79350. if (space == BABYLON.Space.LOCAL) {
  79351. var lm = this.getLocalMatrix();
  79352. result.x = lm.m[12];
  79353. result.y = lm.m[13];
  79354. result.z = lm.m[14];
  79355. }
  79356. else {
  79357. var wm = null;
  79358. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79359. if (mesh) {
  79360. wm = mesh.getWorldMatrix();
  79361. }
  79362. this._skeleton.computeAbsoluteTransforms();
  79363. var tmat = Bone._tmpMats[0];
  79364. if (mesh && wm) {
  79365. tmat.copyFrom(this.getAbsoluteTransform());
  79366. tmat.multiplyToRef(wm, tmat);
  79367. }
  79368. else {
  79369. tmat = this.getAbsoluteTransform();
  79370. }
  79371. result.x = tmat.m[12];
  79372. result.y = tmat.m[13];
  79373. result.z = tmat.m[14];
  79374. }
  79375. };
  79376. /**
  79377. * Get the absolute position of the bone (world space)
  79378. * @param mesh The mesh that this bone is attached to
  79379. * @returns The absolute position of the bone
  79380. */
  79381. Bone.prototype.getAbsolutePosition = function (mesh) {
  79382. if (mesh === void 0) { mesh = null; }
  79383. var pos = BABYLON.Vector3.Zero();
  79384. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  79385. return pos;
  79386. };
  79387. /**
  79388. * Copy the absolute position of the bone (world space) to the result param
  79389. * @param mesh The mesh that this bone is attached to
  79390. * @param result The vector3 to copy the absolute position to
  79391. */
  79392. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  79393. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  79394. };
  79395. /**
  79396. * Compute the absolute transforms of this bone and its children
  79397. */
  79398. Bone.prototype.computeAbsoluteTransforms = function () {
  79399. this._compose();
  79400. if (this._parent) {
  79401. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  79402. }
  79403. else {
  79404. this._absoluteTransform.copyFrom(this._localMatrix);
  79405. var poseMatrix = this._skeleton.getPoseMatrix();
  79406. if (poseMatrix) {
  79407. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  79408. }
  79409. }
  79410. var children = this.children;
  79411. var len = children.length;
  79412. for (var i = 0; i < len; i++) {
  79413. children[i].computeAbsoluteTransforms();
  79414. }
  79415. };
  79416. /**
  79417. * Get the world direction from an axis that is in the local space of the bone
  79418. * @param localAxis The local direction that is used to compute the world direction
  79419. * @param mesh The mesh that this bone is attached to
  79420. * @returns The world direction
  79421. */
  79422. Bone.prototype.getDirection = function (localAxis, mesh) {
  79423. if (mesh === void 0) { mesh = null; }
  79424. var result = BABYLON.Vector3.Zero();
  79425. this.getDirectionToRef(localAxis, mesh, result);
  79426. return result;
  79427. };
  79428. /**
  79429. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  79430. * @param localAxis The local direction that is used to compute the world direction
  79431. * @param mesh The mesh that this bone is attached to
  79432. * @param result The vector3 that the world direction will be copied to
  79433. */
  79434. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  79435. if (mesh === void 0) { mesh = null; }
  79436. var wm = null;
  79437. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79438. if (mesh) {
  79439. wm = mesh.getWorldMatrix();
  79440. }
  79441. this._skeleton.computeAbsoluteTransforms();
  79442. var mat = Bone._tmpMats[0];
  79443. mat.copyFrom(this.getAbsoluteTransform());
  79444. if (mesh && wm) {
  79445. mat.multiplyToRef(wm, mat);
  79446. }
  79447. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  79448. result.normalize();
  79449. };
  79450. /**
  79451. * Get the euler rotation of the bone in local or world space
  79452. * @param space The space that the rotation should be in
  79453. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79454. * @returns The euler rotation
  79455. */
  79456. Bone.prototype.getRotation = function (space, mesh) {
  79457. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79458. if (mesh === void 0) { mesh = null; }
  79459. var result = BABYLON.Vector3.Zero();
  79460. this.getRotationToRef(space, mesh, result);
  79461. return result;
  79462. };
  79463. /**
  79464. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  79465. * @param space The space that the rotation should be in
  79466. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79467. * @param result The vector3 that the rotation should be copied to
  79468. */
  79469. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  79470. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79471. if (mesh === void 0) { mesh = null; }
  79472. var quat = Bone._tmpQuat;
  79473. this.getRotationQuaternionToRef(space, mesh, quat);
  79474. quat.toEulerAnglesToRef(result);
  79475. };
  79476. /**
  79477. * Get the quaternion rotation of the bone in either local or world space
  79478. * @param space The space that the rotation should be in
  79479. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79480. * @returns The quaternion rotation
  79481. */
  79482. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  79483. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79484. if (mesh === void 0) { mesh = null; }
  79485. var result = BABYLON.Quaternion.Identity();
  79486. this.getRotationQuaternionToRef(space, mesh, result);
  79487. return result;
  79488. };
  79489. /**
  79490. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  79491. * @param space The space that the rotation should be in
  79492. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79493. * @param result The quaternion that the rotation should be copied to
  79494. */
  79495. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  79496. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79497. if (mesh === void 0) { mesh = null; }
  79498. if (space == BABYLON.Space.LOCAL) {
  79499. this._decompose();
  79500. result.copyFrom(this._localRotation);
  79501. }
  79502. else {
  79503. var mat = Bone._tmpMats[0];
  79504. var amat = this.getAbsoluteTransform();
  79505. if (mesh) {
  79506. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  79507. }
  79508. else {
  79509. mat.copyFrom(amat);
  79510. }
  79511. mat.m[0] *= this._scalingDeterminant;
  79512. mat.m[1] *= this._scalingDeterminant;
  79513. mat.m[2] *= this._scalingDeterminant;
  79514. mat.decompose(undefined, result, undefined);
  79515. }
  79516. };
  79517. /**
  79518. * Get the rotation matrix of the bone in local or world space
  79519. * @param space The space that the rotation should be in
  79520. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79521. * @returns The rotation matrix
  79522. */
  79523. Bone.prototype.getRotationMatrix = function (space, mesh) {
  79524. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79525. var result = BABYLON.Matrix.Identity();
  79526. this.getRotationMatrixToRef(space, mesh, result);
  79527. return result;
  79528. };
  79529. /**
  79530. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  79531. * @param space The space that the rotation should be in
  79532. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79533. * @param result The quaternion that the rotation should be copied to
  79534. */
  79535. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  79536. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79537. if (space == BABYLON.Space.LOCAL) {
  79538. this.getLocalMatrix().getRotationMatrixToRef(result);
  79539. }
  79540. else {
  79541. var mat = Bone._tmpMats[0];
  79542. var amat = this.getAbsoluteTransform();
  79543. if (mesh) {
  79544. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  79545. }
  79546. else {
  79547. mat.copyFrom(amat);
  79548. }
  79549. mat.m[0] *= this._scalingDeterminant;
  79550. mat.m[1] *= this._scalingDeterminant;
  79551. mat.m[2] *= this._scalingDeterminant;
  79552. mat.getRotationMatrixToRef(result);
  79553. }
  79554. };
  79555. /**
  79556. * Get the world position of a point that is in the local space of the bone
  79557. * @param position The local position
  79558. * @param mesh The mesh that this bone is attached to
  79559. * @returns The world position
  79560. */
  79561. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  79562. if (mesh === void 0) { mesh = null; }
  79563. var result = BABYLON.Vector3.Zero();
  79564. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  79565. return result;
  79566. };
  79567. /**
  79568. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  79569. * @param position The local position
  79570. * @param mesh The mesh that this bone is attached to
  79571. * @param result The vector3 that the world position should be copied to
  79572. */
  79573. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  79574. if (mesh === void 0) { mesh = null; }
  79575. var wm = null;
  79576. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79577. if (mesh) {
  79578. wm = mesh.getWorldMatrix();
  79579. }
  79580. this._skeleton.computeAbsoluteTransforms();
  79581. var tmat = Bone._tmpMats[0];
  79582. if (mesh && wm) {
  79583. tmat.copyFrom(this.getAbsoluteTransform());
  79584. tmat.multiplyToRef(wm, tmat);
  79585. }
  79586. else {
  79587. tmat = this.getAbsoluteTransform();
  79588. }
  79589. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  79590. };
  79591. /**
  79592. * Get the local position of a point that is in world space
  79593. * @param position The world position
  79594. * @param mesh The mesh that this bone is attached to
  79595. * @returns The local position
  79596. */
  79597. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  79598. if (mesh === void 0) { mesh = null; }
  79599. var result = BABYLON.Vector3.Zero();
  79600. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  79601. return result;
  79602. };
  79603. /**
  79604. * Get the local position of a point that is in world space and copy it to the result param
  79605. * @param position The world position
  79606. * @param mesh The mesh that this bone is attached to
  79607. * @param result The vector3 that the local position should be copied to
  79608. */
  79609. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  79610. if (mesh === void 0) { mesh = null; }
  79611. var wm = null;
  79612. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79613. if (mesh) {
  79614. wm = mesh.getWorldMatrix();
  79615. }
  79616. this._skeleton.computeAbsoluteTransforms();
  79617. var tmat = Bone._tmpMats[0];
  79618. tmat.copyFrom(this.getAbsoluteTransform());
  79619. if (mesh && wm) {
  79620. tmat.multiplyToRef(wm, tmat);
  79621. }
  79622. tmat.invert();
  79623. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  79624. };
  79625. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79626. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  79627. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79628. return Bone;
  79629. }(BABYLON.Node));
  79630. BABYLON.Bone = Bone;
  79631. })(BABYLON || (BABYLON = {}));
  79632. //# sourceMappingURL=babylon.bone.js.map
  79633. var BABYLON;
  79634. (function (BABYLON) {
  79635. /**
  79636. * Class used to apply inverse kinematics to bones
  79637. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  79638. */
  79639. var BoneIKController = /** @class */ (function () {
  79640. /**
  79641. * Creates a new BoneIKController
  79642. * @param mesh defines the mesh to control
  79643. * @param bone defines the bone to control
  79644. * @param options defines options to set up the controller
  79645. */
  79646. function BoneIKController(mesh, bone, options) {
  79647. /**
  79648. * Gets or sets the target position
  79649. */
  79650. this.targetPosition = BABYLON.Vector3.Zero();
  79651. /**
  79652. * Gets or sets the pole target position
  79653. */
  79654. this.poleTargetPosition = BABYLON.Vector3.Zero();
  79655. /**
  79656. * Gets or sets the pole target local offset
  79657. */
  79658. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  79659. /**
  79660. * Gets or sets the pole angle
  79661. */
  79662. this.poleAngle = 0;
  79663. /**
  79664. * 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)
  79665. */
  79666. this.slerpAmount = 1;
  79667. this._bone1Quat = BABYLON.Quaternion.Identity();
  79668. this._bone1Mat = BABYLON.Matrix.Identity();
  79669. this._bone2Ang = Math.PI;
  79670. this._maxAngle = Math.PI;
  79671. this._rightHandedSystem = false;
  79672. this._bendAxis = BABYLON.Vector3.Right();
  79673. this._slerping = false;
  79674. this._adjustRoll = 0;
  79675. this._bone2 = bone;
  79676. this._bone1 = bone.getParent();
  79677. if (!this._bone1) {
  79678. return;
  79679. }
  79680. this.mesh = mesh;
  79681. var bonePos = bone.getPosition();
  79682. if (bone.getAbsoluteTransform().determinant() > 0) {
  79683. this._rightHandedSystem = true;
  79684. this._bendAxis.x = 0;
  79685. this._bendAxis.y = 0;
  79686. this._bendAxis.z = -1;
  79687. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  79688. this._adjustRoll = Math.PI * .5;
  79689. this._bendAxis.z = 1;
  79690. }
  79691. }
  79692. if (this._bone1.length) {
  79693. var boneScale1 = this._bone1.getScale();
  79694. var boneScale2 = this._bone2.getScale();
  79695. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  79696. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  79697. }
  79698. else if (this._bone1.children[0]) {
  79699. mesh.computeWorldMatrix(true);
  79700. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  79701. var pos2 = this._bone2.getAbsolutePosition(mesh);
  79702. var pos3 = this._bone1.getAbsolutePosition(mesh);
  79703. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  79704. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  79705. }
  79706. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  79707. this.maxAngle = Math.PI;
  79708. if (options) {
  79709. if (options.targetMesh) {
  79710. this.targetMesh = options.targetMesh;
  79711. this.targetMesh.computeWorldMatrix(true);
  79712. }
  79713. if (options.poleTargetMesh) {
  79714. this.poleTargetMesh = options.poleTargetMesh;
  79715. this.poleTargetMesh.computeWorldMatrix(true);
  79716. }
  79717. else if (options.poleTargetBone) {
  79718. this.poleTargetBone = options.poleTargetBone;
  79719. }
  79720. else if (this._bone1.getParent()) {
  79721. this.poleTargetBone = this._bone1.getParent();
  79722. }
  79723. if (options.poleTargetLocalOffset) {
  79724. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  79725. }
  79726. if (options.poleAngle) {
  79727. this.poleAngle = options.poleAngle;
  79728. }
  79729. if (options.bendAxis) {
  79730. this._bendAxis.copyFrom(options.bendAxis);
  79731. }
  79732. if (options.maxAngle) {
  79733. this.maxAngle = options.maxAngle;
  79734. }
  79735. if (options.slerpAmount) {
  79736. this.slerpAmount = options.slerpAmount;
  79737. }
  79738. }
  79739. }
  79740. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  79741. /**
  79742. * Gets or sets maximum allowed angle
  79743. */
  79744. get: function () {
  79745. return this._maxAngle;
  79746. },
  79747. set: function (value) {
  79748. this._setMaxAngle(value);
  79749. },
  79750. enumerable: true,
  79751. configurable: true
  79752. });
  79753. BoneIKController.prototype._setMaxAngle = function (ang) {
  79754. if (ang < 0) {
  79755. ang = 0;
  79756. }
  79757. if (ang > Math.PI || ang == undefined) {
  79758. ang = Math.PI;
  79759. }
  79760. this._maxAngle = ang;
  79761. var a = this._bone1Length;
  79762. var b = this._bone2Length;
  79763. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  79764. };
  79765. /**
  79766. * Force the controller to update the bones
  79767. */
  79768. BoneIKController.prototype.update = function () {
  79769. var bone1 = this._bone1;
  79770. if (!bone1) {
  79771. return;
  79772. }
  79773. var target = this.targetPosition;
  79774. var poleTarget = this.poleTargetPosition;
  79775. var mat1 = BoneIKController._tmpMats[0];
  79776. var mat2 = BoneIKController._tmpMats[1];
  79777. if (this.targetMesh) {
  79778. target.copyFrom(this.targetMesh.getAbsolutePosition());
  79779. }
  79780. if (this.poleTargetBone) {
  79781. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  79782. }
  79783. else if (this.poleTargetMesh) {
  79784. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  79785. }
  79786. var bonePos = BoneIKController._tmpVecs[0];
  79787. var zaxis = BoneIKController._tmpVecs[1];
  79788. var xaxis = BoneIKController._tmpVecs[2];
  79789. var yaxis = BoneIKController._tmpVecs[3];
  79790. var upAxis = BoneIKController._tmpVecs[4];
  79791. var _tmpQuat = BoneIKController._tmpQuat;
  79792. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  79793. poleTarget.subtractToRef(bonePos, upAxis);
  79794. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  79795. upAxis.y = 1;
  79796. }
  79797. else {
  79798. upAxis.normalize();
  79799. }
  79800. target.subtractToRef(bonePos, yaxis);
  79801. yaxis.normalize();
  79802. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  79803. zaxis.normalize();
  79804. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  79805. xaxis.normalize();
  79806. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  79807. var a = this._bone1Length;
  79808. var b = this._bone2Length;
  79809. var c = BABYLON.Vector3.Distance(bonePos, target);
  79810. if (this._maxReach > 0) {
  79811. c = Math.min(this._maxReach, c);
  79812. }
  79813. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  79814. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  79815. if (acosa > 1) {
  79816. acosa = 1;
  79817. }
  79818. if (acosb > 1) {
  79819. acosb = 1;
  79820. }
  79821. if (acosa < -1) {
  79822. acosa = -1;
  79823. }
  79824. if (acosb < -1) {
  79825. acosb = -1;
  79826. }
  79827. var angA = Math.acos(acosa);
  79828. var angB = Math.acos(acosb);
  79829. var angC = -angA - angB;
  79830. if (this._rightHandedSystem) {
  79831. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  79832. mat2.multiplyToRef(mat1, mat1);
  79833. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  79834. mat2.multiplyToRef(mat1, mat1);
  79835. }
  79836. else {
  79837. var _tmpVec = BoneIKController._tmpVecs[5];
  79838. _tmpVec.copyFrom(this._bendAxis);
  79839. _tmpVec.x *= -1;
  79840. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  79841. mat2.multiplyToRef(mat1, mat1);
  79842. }
  79843. if (this.poleAngle) {
  79844. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  79845. mat1.multiplyToRef(mat2, mat1);
  79846. }
  79847. if (this._bone1) {
  79848. if (this.slerpAmount < 1) {
  79849. if (!this._slerping) {
  79850. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  79851. }
  79852. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  79853. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  79854. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  79855. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  79856. this._slerping = true;
  79857. }
  79858. else {
  79859. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  79860. this._bone1Mat.copyFrom(mat1);
  79861. this._slerping = false;
  79862. }
  79863. }
  79864. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  79865. this._bone2Ang = angC;
  79866. };
  79867. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79868. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  79869. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79870. return BoneIKController;
  79871. }());
  79872. BABYLON.BoneIKController = BoneIKController;
  79873. })(BABYLON || (BABYLON = {}));
  79874. //# sourceMappingURL=babylon.boneIKController.js.map
  79875. var BABYLON;
  79876. (function (BABYLON) {
  79877. /**
  79878. * Class used to make a bone look toward a point in space
  79879. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  79880. */
  79881. var BoneLookController = /** @class */ (function () {
  79882. /**
  79883. * Create a BoneLookController
  79884. * @param mesh the mesh that the bone belongs to
  79885. * @param bone the bone that will be looking to the target
  79886. * @param target the target Vector3 to look at
  79887. * @param settings optional settings:
  79888. * * maxYaw: the maximum angle the bone will yaw to
  79889. * * minYaw: the minimum angle the bone will yaw to
  79890. * * maxPitch: the maximum angle the bone will pitch to
  79891. * * minPitch: the minimum angle the bone will yaw to
  79892. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  79893. * * upAxis: the up axis of the coordinate system
  79894. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  79895. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  79896. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  79897. * * adjustYaw: used to make an adjustment to the yaw of the bone
  79898. * * adjustPitch: used to make an adjustment to the pitch of the bone
  79899. * * adjustRoll: used to make an adjustment to the roll of the bone
  79900. **/
  79901. function BoneLookController(mesh, bone, target, options) {
  79902. /**
  79903. * The up axis of the coordinate system that is used when the bone is rotated
  79904. */
  79905. this.upAxis = BABYLON.Vector3.Up();
  79906. /**
  79907. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  79908. */
  79909. this.upAxisSpace = BABYLON.Space.LOCAL;
  79910. /**
  79911. * Used to make an adjustment to the yaw of the bone
  79912. */
  79913. this.adjustYaw = 0;
  79914. /**
  79915. * Used to make an adjustment to the pitch of the bone
  79916. */
  79917. this.adjustPitch = 0;
  79918. /**
  79919. * Used to make an adjustment to the roll of the bone
  79920. */
  79921. this.adjustRoll = 0;
  79922. /**
  79923. * 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)
  79924. */
  79925. this.slerpAmount = 1;
  79926. this._boneQuat = BABYLON.Quaternion.Identity();
  79927. this._slerping = false;
  79928. this._firstFrameSkipped = false;
  79929. this._fowardAxis = BABYLON.Vector3.Forward();
  79930. this.mesh = mesh;
  79931. this.bone = bone;
  79932. this.target = target;
  79933. if (options) {
  79934. if (options.adjustYaw) {
  79935. this.adjustYaw = options.adjustYaw;
  79936. }
  79937. if (options.adjustPitch) {
  79938. this.adjustPitch = options.adjustPitch;
  79939. }
  79940. if (options.adjustRoll) {
  79941. this.adjustRoll = options.adjustRoll;
  79942. }
  79943. if (options.maxYaw != null) {
  79944. this.maxYaw = options.maxYaw;
  79945. }
  79946. else {
  79947. this.maxYaw = Math.PI;
  79948. }
  79949. if (options.minYaw != null) {
  79950. this.minYaw = options.minYaw;
  79951. }
  79952. else {
  79953. this.minYaw = -Math.PI;
  79954. }
  79955. if (options.maxPitch != null) {
  79956. this.maxPitch = options.maxPitch;
  79957. }
  79958. else {
  79959. this.maxPitch = Math.PI;
  79960. }
  79961. if (options.minPitch != null) {
  79962. this.minPitch = options.minPitch;
  79963. }
  79964. else {
  79965. this.minPitch = -Math.PI;
  79966. }
  79967. if (options.slerpAmount != null) {
  79968. this.slerpAmount = options.slerpAmount;
  79969. }
  79970. if (options.upAxis != null) {
  79971. this.upAxis = options.upAxis;
  79972. }
  79973. if (options.upAxisSpace != null) {
  79974. this.upAxisSpace = options.upAxisSpace;
  79975. }
  79976. if (options.yawAxis != null || options.pitchAxis != null) {
  79977. var newYawAxis = BABYLON.Axis.Y;
  79978. var newPitchAxis = BABYLON.Axis.X;
  79979. if (options.yawAxis != null) {
  79980. newYawAxis = options.yawAxis.clone();
  79981. newYawAxis.normalize();
  79982. }
  79983. if (options.pitchAxis != null) {
  79984. newPitchAxis = options.pitchAxis.clone();
  79985. newPitchAxis.normalize();
  79986. }
  79987. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  79988. this._transformYawPitch = BABYLON.Matrix.Identity();
  79989. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  79990. this._transformYawPitchInv = this._transformYawPitch.clone();
  79991. this._transformYawPitch.invert();
  79992. }
  79993. }
  79994. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  79995. this.upAxisSpace = BABYLON.Space.LOCAL;
  79996. }
  79997. }
  79998. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  79999. /**
  80000. * Gets or sets the minimum yaw angle that the bone can look to
  80001. */
  80002. get: function () {
  80003. return this._minYaw;
  80004. },
  80005. set: function (value) {
  80006. this._minYaw = value;
  80007. this._minYawSin = Math.sin(value);
  80008. this._minYawCos = Math.cos(value);
  80009. if (this._maxYaw != null) {
  80010. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  80011. this._yawRange = this._maxYaw - this._minYaw;
  80012. }
  80013. },
  80014. enumerable: true,
  80015. configurable: true
  80016. });
  80017. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  80018. /**
  80019. * Gets or sets the maximum yaw angle that the bone can look to
  80020. */
  80021. get: function () {
  80022. return this._maxYaw;
  80023. },
  80024. set: function (value) {
  80025. this._maxYaw = value;
  80026. this._maxYawSin = Math.sin(value);
  80027. this._maxYawCos = Math.cos(value);
  80028. if (this._minYaw != null) {
  80029. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  80030. this._yawRange = this._maxYaw - this._minYaw;
  80031. }
  80032. },
  80033. enumerable: true,
  80034. configurable: true
  80035. });
  80036. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  80037. /**
  80038. * Gets or sets the minimum pitch angle that the bone can look to
  80039. */
  80040. get: function () {
  80041. return this._minPitch;
  80042. },
  80043. set: function (value) {
  80044. this._minPitch = value;
  80045. this._minPitchTan = Math.tan(value);
  80046. },
  80047. enumerable: true,
  80048. configurable: true
  80049. });
  80050. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  80051. /**
  80052. * Gets or sets the maximum pitch angle that the bone can look to
  80053. */
  80054. get: function () {
  80055. return this._maxPitch;
  80056. },
  80057. set: function (value) {
  80058. this._maxPitch = value;
  80059. this._maxPitchTan = Math.tan(value);
  80060. },
  80061. enumerable: true,
  80062. configurable: true
  80063. });
  80064. /**
  80065. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  80066. */
  80067. BoneLookController.prototype.update = function () {
  80068. //skip the first frame when slerping so that the mesh rotation is correct
  80069. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  80070. this._firstFrameSkipped = true;
  80071. return;
  80072. }
  80073. var bone = this.bone;
  80074. var bonePos = BoneLookController._tmpVecs[0];
  80075. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  80076. var target = this.target;
  80077. var _tmpMat1 = BoneLookController._tmpMats[0];
  80078. var _tmpMat2 = BoneLookController._tmpMats[1];
  80079. var mesh = this.mesh;
  80080. var parentBone = bone.getParent();
  80081. var upAxis = BoneLookController._tmpVecs[1];
  80082. upAxis.copyFrom(this.upAxis);
  80083. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  80084. if (this._transformYawPitch) {
  80085. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  80086. }
  80087. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  80088. }
  80089. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  80090. mesh.getDirectionToRef(upAxis, upAxis);
  80091. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  80092. upAxis.normalize();
  80093. }
  80094. }
  80095. var checkYaw = false;
  80096. var checkPitch = false;
  80097. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  80098. checkYaw = true;
  80099. }
  80100. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  80101. checkPitch = true;
  80102. }
  80103. if (checkYaw || checkPitch) {
  80104. var spaceMat = BoneLookController._tmpMats[2];
  80105. var spaceMatInv = BoneLookController._tmpMats[3];
  80106. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  80107. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  80108. }
  80109. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  80110. spaceMat.copyFrom(mesh.getWorldMatrix());
  80111. }
  80112. else {
  80113. var forwardAxis = BoneLookController._tmpVecs[2];
  80114. forwardAxis.copyFrom(this._fowardAxis);
  80115. if (this._transformYawPitch) {
  80116. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  80117. }
  80118. if (parentBone) {
  80119. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  80120. }
  80121. else {
  80122. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  80123. }
  80124. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  80125. rightAxis.normalize();
  80126. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  80127. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  80128. }
  80129. spaceMat.invertToRef(spaceMatInv);
  80130. var xzlen = null;
  80131. if (checkPitch) {
  80132. var localTarget = BoneLookController._tmpVecs[3];
  80133. target.subtractToRef(bonePos, localTarget);
  80134. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  80135. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80136. var pitch = Math.atan2(localTarget.y, xzlen);
  80137. var newPitch = pitch;
  80138. if (pitch > this._maxPitch) {
  80139. localTarget.y = this._maxPitchTan * xzlen;
  80140. newPitch = this._maxPitch;
  80141. }
  80142. else if (pitch < this._minPitch) {
  80143. localTarget.y = this._minPitchTan * xzlen;
  80144. newPitch = this._minPitch;
  80145. }
  80146. if (pitch != newPitch) {
  80147. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  80148. localTarget.addInPlace(bonePos);
  80149. target = localTarget;
  80150. }
  80151. }
  80152. if (checkYaw) {
  80153. var localTarget = BoneLookController._tmpVecs[4];
  80154. target.subtractToRef(bonePos, localTarget);
  80155. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  80156. var yaw = Math.atan2(localTarget.x, localTarget.z);
  80157. var newYaw = yaw;
  80158. if (yaw > this._maxYaw || yaw < this._minYaw) {
  80159. if (xzlen == null) {
  80160. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80161. }
  80162. if (this._yawRange > Math.PI) {
  80163. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  80164. localTarget.z = this._maxYawCos * xzlen;
  80165. localTarget.x = this._maxYawSin * xzlen;
  80166. newYaw = this._maxYaw;
  80167. }
  80168. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  80169. localTarget.z = this._minYawCos * xzlen;
  80170. localTarget.x = this._minYawSin * xzlen;
  80171. newYaw = this._minYaw;
  80172. }
  80173. }
  80174. else {
  80175. if (yaw > this._maxYaw) {
  80176. localTarget.z = this._maxYawCos * xzlen;
  80177. localTarget.x = this._maxYawSin * xzlen;
  80178. newYaw = this._maxYaw;
  80179. }
  80180. else if (yaw < this._minYaw) {
  80181. localTarget.z = this._minYawCos * xzlen;
  80182. localTarget.x = this._minYawSin * xzlen;
  80183. newYaw = this._minYaw;
  80184. }
  80185. }
  80186. }
  80187. if (this._slerping && this._yawRange > Math.PI) {
  80188. //are we going to be crossing into the min/max region?
  80189. var boneFwd = BoneLookController._tmpVecs[8];
  80190. boneFwd.copyFrom(BABYLON.Axis.Z);
  80191. if (this._transformYawPitch) {
  80192. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  80193. }
  80194. var boneRotMat = BoneLookController._tmpMats[4];
  80195. this._boneQuat.toRotationMatrix(boneRotMat);
  80196. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  80197. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  80198. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  80199. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  80200. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  80201. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  80202. if (angBtwTar > angBtwMidYaw) {
  80203. if (xzlen == null) {
  80204. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80205. }
  80206. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  80207. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  80208. if (angBtwMin < angBtwMax) {
  80209. newYaw = boneYaw + Math.PI * .75;
  80210. localTarget.z = Math.cos(newYaw) * xzlen;
  80211. localTarget.x = Math.sin(newYaw) * xzlen;
  80212. }
  80213. else {
  80214. newYaw = boneYaw - Math.PI * .75;
  80215. localTarget.z = Math.cos(newYaw) * xzlen;
  80216. localTarget.x = Math.sin(newYaw) * xzlen;
  80217. }
  80218. }
  80219. }
  80220. if (yaw != newYaw) {
  80221. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  80222. localTarget.addInPlace(bonePos);
  80223. target = localTarget;
  80224. }
  80225. }
  80226. }
  80227. var zaxis = BoneLookController._tmpVecs[5];
  80228. var xaxis = BoneLookController._tmpVecs[6];
  80229. var yaxis = BoneLookController._tmpVecs[7];
  80230. var _tmpQuat = BoneLookController._tmpQuat;
  80231. target.subtractToRef(bonePos, zaxis);
  80232. zaxis.normalize();
  80233. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  80234. xaxis.normalize();
  80235. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  80236. yaxis.normalize();
  80237. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  80238. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  80239. return;
  80240. }
  80241. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  80242. return;
  80243. }
  80244. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  80245. return;
  80246. }
  80247. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  80248. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  80249. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  80250. }
  80251. if (this.slerpAmount < 1) {
  80252. if (!this._slerping) {
  80253. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  80254. }
  80255. if (this._transformYawPitch) {
  80256. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  80257. }
  80258. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  80259. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  80260. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  80261. this._slerping = true;
  80262. }
  80263. else {
  80264. if (this._transformYawPitch) {
  80265. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  80266. }
  80267. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  80268. this._slerping = false;
  80269. }
  80270. };
  80271. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  80272. var angDiff = ang2 - ang1;
  80273. angDiff %= Math.PI * 2;
  80274. if (angDiff > Math.PI) {
  80275. angDiff -= Math.PI * 2;
  80276. }
  80277. else if (angDiff < -Math.PI) {
  80278. angDiff += Math.PI * 2;
  80279. }
  80280. return angDiff;
  80281. };
  80282. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  80283. ang1 %= (2 * Math.PI);
  80284. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  80285. ang2 %= (2 * Math.PI);
  80286. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  80287. var ab = 0;
  80288. if (ang1 < ang2) {
  80289. ab = ang2 - ang1;
  80290. }
  80291. else {
  80292. ab = ang1 - ang2;
  80293. }
  80294. if (ab > Math.PI) {
  80295. ab = Math.PI * 2 - ab;
  80296. }
  80297. return ab;
  80298. };
  80299. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  80300. ang %= (2 * Math.PI);
  80301. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  80302. ang1 %= (2 * Math.PI);
  80303. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  80304. ang2 %= (2 * Math.PI);
  80305. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  80306. if (ang1 < ang2) {
  80307. if (ang > ang1 && ang < ang2) {
  80308. return true;
  80309. }
  80310. }
  80311. else {
  80312. if (ang > ang2 && ang < ang1) {
  80313. return true;
  80314. }
  80315. }
  80316. return false;
  80317. };
  80318. 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()];
  80319. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  80320. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80321. return BoneLookController;
  80322. }());
  80323. BABYLON.BoneLookController = BoneLookController;
  80324. })(BABYLON || (BABYLON = {}));
  80325. //# sourceMappingURL=babylon.boneLookController.js.map
  80326. var BABYLON;
  80327. (function (BABYLON) {
  80328. /**
  80329. * Class used to handle skinning animations
  80330. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  80331. */
  80332. var Skeleton = /** @class */ (function () {
  80333. /**
  80334. * Creates a new skeleton
  80335. * @param name defines the skeleton name
  80336. * @param id defines the skeleton Id
  80337. * @param scene defines the hosting scene
  80338. */
  80339. function Skeleton(
  80340. /** defines the skeleton name */
  80341. name,
  80342. /** defines the skeleton Id */
  80343. id, scene) {
  80344. this.name = name;
  80345. this.id = id;
  80346. /**
  80347. * Gets the list of child bones
  80348. */
  80349. this.bones = new Array();
  80350. /**
  80351. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  80352. */
  80353. this.needInitialSkinMatrix = false;
  80354. this._isDirty = true;
  80355. this._meshesWithPoseMatrix = new Array();
  80356. this._identity = BABYLON.Matrix.Identity();
  80357. this._ranges = {};
  80358. this._lastAbsoluteTransformsUpdateId = -1;
  80359. /**
  80360. * Specifies if the skeleton should be serialized
  80361. */
  80362. this.doNotSerialize = false;
  80363. this._animationPropertiesOverride = null;
  80364. // Events
  80365. /**
  80366. * An observable triggered before computing the skeleton's matrices
  80367. */
  80368. this.onBeforeComputeObservable = new BABYLON.Observable();
  80369. this.bones = [];
  80370. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80371. scene.skeletons.push(this);
  80372. //make sure it will recalculate the matrix next time prepare is called.
  80373. this._isDirty = true;
  80374. }
  80375. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  80376. /**
  80377. * Gets or sets the animation properties override
  80378. */
  80379. get: function () {
  80380. if (!this._animationPropertiesOverride) {
  80381. return this._scene.animationPropertiesOverride;
  80382. }
  80383. return this._animationPropertiesOverride;
  80384. },
  80385. set: function (value) {
  80386. this._animationPropertiesOverride = value;
  80387. },
  80388. enumerable: true,
  80389. configurable: true
  80390. });
  80391. // Members
  80392. /**
  80393. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  80394. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  80395. * @returns a Float32Array containing matrices data
  80396. */
  80397. Skeleton.prototype.getTransformMatrices = function (mesh) {
  80398. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  80399. return mesh._bonesTransformMatrices;
  80400. }
  80401. if (!this._transformMatrices) {
  80402. this.prepare();
  80403. }
  80404. return this._transformMatrices;
  80405. };
  80406. /**
  80407. * Gets the current hosting scene
  80408. * @returns a scene object
  80409. */
  80410. Skeleton.prototype.getScene = function () {
  80411. return this._scene;
  80412. };
  80413. // Methods
  80414. /**
  80415. * Gets a string representing the current skeleton data
  80416. * @param fullDetails defines a boolean indicating if we want a verbose version
  80417. * @returns a string representing the current skeleton data
  80418. */
  80419. Skeleton.prototype.toString = function (fullDetails) {
  80420. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  80421. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  80422. if (fullDetails) {
  80423. ret += ", Ranges: {";
  80424. var first = true;
  80425. for (var name_1 in this._ranges) {
  80426. if (first) {
  80427. ret += ", ";
  80428. first = false;
  80429. }
  80430. ret += name_1;
  80431. }
  80432. ret += "}";
  80433. }
  80434. return ret;
  80435. };
  80436. /**
  80437. * Get bone's index searching by name
  80438. * @param name defines bone's name to search for
  80439. * @return the indice of the bone. Returns -1 if not found
  80440. */
  80441. Skeleton.prototype.getBoneIndexByName = function (name) {
  80442. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  80443. if (this.bones[boneIndex].name === name) {
  80444. return boneIndex;
  80445. }
  80446. }
  80447. return -1;
  80448. };
  80449. /**
  80450. * Creater a new animation range
  80451. * @param name defines the name of the range
  80452. * @param from defines the start key
  80453. * @param to defines the end key
  80454. */
  80455. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  80456. // check name not already in use
  80457. if (!this._ranges[name]) {
  80458. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  80459. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80460. if (this.bones[i].animations[0]) {
  80461. this.bones[i].animations[0].createRange(name, from, to);
  80462. }
  80463. }
  80464. }
  80465. };
  80466. /**
  80467. * Delete a specific animation range
  80468. * @param name defines the name of the range
  80469. * @param deleteFrames defines if frames must be removed as well
  80470. */
  80471. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  80472. if (deleteFrames === void 0) { deleteFrames = true; }
  80473. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80474. if (this.bones[i].animations[0]) {
  80475. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  80476. }
  80477. }
  80478. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  80479. };
  80480. /**
  80481. * Gets a specific animation range
  80482. * @param name defines the name of the range to look for
  80483. * @returns the requested animation range or null if not found
  80484. */
  80485. Skeleton.prototype.getAnimationRange = function (name) {
  80486. return this._ranges[name];
  80487. };
  80488. /**
  80489. * Gets the list of all animation ranges defined on this skeleton
  80490. * @returns an array
  80491. */
  80492. Skeleton.prototype.getAnimationRanges = function () {
  80493. var animationRanges = [];
  80494. var name;
  80495. var i = 0;
  80496. for (name in this._ranges) {
  80497. animationRanges[i] = this._ranges[name];
  80498. i++;
  80499. }
  80500. return animationRanges;
  80501. };
  80502. /**
  80503. * Copy animation range from a source skeleton.
  80504. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  80505. * @param source defines the source skeleton
  80506. * @param name defines the name of the range to copy
  80507. * @param rescaleAsRequired defines if rescaling must be applied if required
  80508. * @returns true if operation was successful
  80509. */
  80510. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  80511. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  80512. if (this._ranges[name] || !source.getAnimationRange(name)) {
  80513. return false;
  80514. }
  80515. var ret = true;
  80516. var frameOffset = this._getHighestAnimationFrame() + 1;
  80517. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  80518. var boneDict = {};
  80519. var sourceBones = source.bones;
  80520. var nBones;
  80521. var i;
  80522. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  80523. boneDict[sourceBones[i].name] = sourceBones[i];
  80524. }
  80525. if (this.bones.length !== sourceBones.length) {
  80526. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  80527. ret = false;
  80528. }
  80529. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  80530. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  80531. var boneName = this.bones[i].name;
  80532. var sourceBone = boneDict[boneName];
  80533. if (sourceBone) {
  80534. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  80535. }
  80536. else {
  80537. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  80538. ret = false;
  80539. }
  80540. }
  80541. // do not call createAnimationRange(), since it also is done to bones, which was already done
  80542. var range = source.getAnimationRange(name);
  80543. if (range) {
  80544. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  80545. }
  80546. return ret;
  80547. };
  80548. /**
  80549. * Forces the skeleton to go to rest pose
  80550. */
  80551. Skeleton.prototype.returnToRest = function () {
  80552. for (var index = 0; index < this.bones.length; index++) {
  80553. this.bones[index].returnToRest();
  80554. }
  80555. };
  80556. Skeleton.prototype._getHighestAnimationFrame = function () {
  80557. var ret = 0;
  80558. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80559. if (this.bones[i].animations[0]) {
  80560. var highest = this.bones[i].animations[0].getHighestFrame();
  80561. if (ret < highest) {
  80562. ret = highest;
  80563. }
  80564. }
  80565. }
  80566. return ret;
  80567. };
  80568. /**
  80569. * Begin a specific animation range
  80570. * @param name defines the name of the range to start
  80571. * @param loop defines if looping must be turned on (false by default)
  80572. * @param speedRatio defines the speed ratio to apply (1 by default)
  80573. * @param onAnimationEnd defines a callback which will be called when animation will end
  80574. * @returns a new animatable
  80575. */
  80576. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  80577. var range = this.getAnimationRange(name);
  80578. if (!range) {
  80579. return null;
  80580. }
  80581. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  80582. };
  80583. /** @hidden */
  80584. Skeleton.prototype._markAsDirty = function () {
  80585. this._isDirty = true;
  80586. };
  80587. /** @hidden */
  80588. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  80589. this._meshesWithPoseMatrix.push(mesh);
  80590. };
  80591. /** @hidden */
  80592. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  80593. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  80594. if (index > -1) {
  80595. this._meshesWithPoseMatrix.splice(index, 1);
  80596. }
  80597. };
  80598. /** @hidden */
  80599. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  80600. this.onBeforeComputeObservable.notifyObservers(this);
  80601. for (var index = 0; index < this.bones.length; index++) {
  80602. var bone = this.bones[index];
  80603. var parentBone = bone.getParent();
  80604. if (parentBone) {
  80605. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  80606. }
  80607. else {
  80608. if (initialSkinMatrix) {
  80609. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  80610. }
  80611. else {
  80612. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  80613. }
  80614. }
  80615. if (bone._index !== -1) {
  80616. var mappedIndex = bone._index === null ? index : bone._index;
  80617. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  80618. }
  80619. }
  80620. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  80621. };
  80622. /**
  80623. * Build all resources required to render a skeleton
  80624. */
  80625. Skeleton.prototype.prepare = function () {
  80626. if (!this._isDirty) {
  80627. return;
  80628. }
  80629. if (this.needInitialSkinMatrix) {
  80630. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  80631. var mesh = this._meshesWithPoseMatrix[index];
  80632. var poseMatrix = mesh.getPoseMatrix();
  80633. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  80634. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  80635. }
  80636. if (this._synchronizedWithMesh !== mesh) {
  80637. this._synchronizedWithMesh = mesh;
  80638. // Prepare bones
  80639. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  80640. var bone = this.bones[boneIndex];
  80641. if (!bone.getParent()) {
  80642. var matrix = bone.getBaseMatrix();
  80643. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  80644. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  80645. }
  80646. }
  80647. }
  80648. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  80649. }
  80650. }
  80651. else {
  80652. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  80653. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  80654. }
  80655. this._computeTransformMatrices(this._transformMatrices, null);
  80656. }
  80657. this._isDirty = false;
  80658. this._scene._activeBones.addCount(this.bones.length, false);
  80659. };
  80660. /**
  80661. * Gets the list of animatables currently running for this skeleton
  80662. * @returns an array of animatables
  80663. */
  80664. Skeleton.prototype.getAnimatables = function () {
  80665. if (!this._animatables || this._animatables.length !== this.bones.length) {
  80666. this._animatables = [];
  80667. for (var index = 0; index < this.bones.length; index++) {
  80668. this._animatables.push(this.bones[index]);
  80669. }
  80670. }
  80671. return this._animatables;
  80672. };
  80673. /**
  80674. * Clone the current skeleton
  80675. * @param name defines the name of the new skeleton
  80676. * @param id defines the id of the enw skeleton
  80677. * @returns the new skeleton
  80678. */
  80679. Skeleton.prototype.clone = function (name, id) {
  80680. var result = new Skeleton(name, id || name, this._scene);
  80681. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80682. for (var index = 0; index < this.bones.length; index++) {
  80683. var source = this.bones[index];
  80684. var parentBone = null;
  80685. var parent_1 = source.getParent();
  80686. if (parent_1) {
  80687. var parentIndex = this.bones.indexOf(parent_1);
  80688. parentBone = result.bones[parentIndex];
  80689. }
  80690. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  80691. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  80692. }
  80693. if (this._ranges) {
  80694. result._ranges = {};
  80695. for (var rangeName in this._ranges) {
  80696. var range = this._ranges[rangeName];
  80697. if (range) {
  80698. result._ranges[rangeName] = range.clone();
  80699. }
  80700. }
  80701. }
  80702. this._isDirty = true;
  80703. return result;
  80704. };
  80705. /**
  80706. * Enable animation blending for this skeleton
  80707. * @param blendingSpeed defines the blending speed to apply
  80708. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  80709. */
  80710. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  80711. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  80712. this.bones.forEach(function (bone) {
  80713. bone.animations.forEach(function (animation) {
  80714. animation.enableBlending = true;
  80715. animation.blendingSpeed = blendingSpeed;
  80716. });
  80717. });
  80718. };
  80719. /**
  80720. * Releases all resources associated with the current skeleton
  80721. */
  80722. Skeleton.prototype.dispose = function () {
  80723. this._meshesWithPoseMatrix = [];
  80724. // Animations
  80725. this.getScene().stopAnimation(this);
  80726. // Remove from scene
  80727. this.getScene().removeSkeleton(this);
  80728. };
  80729. /**
  80730. * Serialize the skeleton in a JSON object
  80731. * @returns a JSON object
  80732. */
  80733. Skeleton.prototype.serialize = function () {
  80734. var serializationObject = {};
  80735. serializationObject.name = this.name;
  80736. serializationObject.id = this.id;
  80737. if (this.dimensionsAtRest) {
  80738. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  80739. }
  80740. serializationObject.bones = [];
  80741. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80742. for (var index = 0; index < this.bones.length; index++) {
  80743. var bone = this.bones[index];
  80744. var parent_2 = bone.getParent();
  80745. var serializedBone = {
  80746. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  80747. name: bone.name,
  80748. matrix: bone.getBaseMatrix().toArray(),
  80749. rest: bone.getRestPose().toArray()
  80750. };
  80751. serializationObject.bones.push(serializedBone);
  80752. if (bone.length) {
  80753. serializedBone.length = bone.length;
  80754. }
  80755. if (bone.metadata) {
  80756. serializedBone.metadata = bone.metadata;
  80757. }
  80758. if (bone.animations && bone.animations.length > 0) {
  80759. serializedBone.animation = bone.animations[0].serialize();
  80760. }
  80761. serializationObject.ranges = [];
  80762. for (var name in this._ranges) {
  80763. var source = this._ranges[name];
  80764. if (!source) {
  80765. continue;
  80766. }
  80767. var range = {};
  80768. range.name = name;
  80769. range.from = source.from;
  80770. range.to = source.to;
  80771. serializationObject.ranges.push(range);
  80772. }
  80773. }
  80774. return serializationObject;
  80775. };
  80776. /**
  80777. * Creates a new skeleton from serialized data
  80778. * @param parsedSkeleton defines the serialized data
  80779. * @param scene defines the hosting scene
  80780. * @returns a new skeleton
  80781. */
  80782. Skeleton.Parse = function (parsedSkeleton, scene) {
  80783. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  80784. if (parsedSkeleton.dimensionsAtRest) {
  80785. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  80786. }
  80787. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  80788. var index;
  80789. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  80790. var parsedBone = parsedSkeleton.bones[index];
  80791. var parentBone = null;
  80792. if (parsedBone.parentBoneIndex > -1) {
  80793. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  80794. }
  80795. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  80796. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  80797. if (parsedBone.length) {
  80798. bone.length = parsedBone.length;
  80799. }
  80800. if (parsedBone.metadata) {
  80801. bone.metadata = parsedBone.metadata;
  80802. }
  80803. if (parsedBone.animation) {
  80804. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  80805. }
  80806. }
  80807. // placed after bones, so createAnimationRange can cascade down
  80808. if (parsedSkeleton.ranges) {
  80809. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  80810. var data = parsedSkeleton.ranges[index];
  80811. skeleton.createAnimationRange(data.name, data.from, data.to);
  80812. }
  80813. }
  80814. return skeleton;
  80815. };
  80816. /**
  80817. * Compute all node absolute transforms
  80818. * @param forceUpdate defines if computation must be done even if cache is up to date
  80819. */
  80820. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  80821. if (forceUpdate === void 0) { forceUpdate = false; }
  80822. var renderId = this._scene.getRenderId();
  80823. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  80824. this.bones[0].computeAbsoluteTransforms();
  80825. this._lastAbsoluteTransformsUpdateId = renderId;
  80826. }
  80827. };
  80828. /**
  80829. * Gets the root pose matrix
  80830. * @returns a matrix
  80831. */
  80832. Skeleton.prototype.getPoseMatrix = function () {
  80833. var poseMatrix = null;
  80834. if (this._meshesWithPoseMatrix.length > 0) {
  80835. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  80836. }
  80837. return poseMatrix;
  80838. };
  80839. /**
  80840. * Sorts bones per internal index
  80841. */
  80842. Skeleton.prototype.sortBones = function () {
  80843. var bones = new Array();
  80844. var visited = new Array(this.bones.length);
  80845. for (var index = 0; index < this.bones.length; index++) {
  80846. this._sortBones(index, bones, visited);
  80847. }
  80848. this.bones = bones;
  80849. };
  80850. Skeleton.prototype._sortBones = function (index, bones, visited) {
  80851. if (visited[index]) {
  80852. return;
  80853. }
  80854. visited[index] = true;
  80855. var bone = this.bones[index];
  80856. if (bone._index === undefined) {
  80857. bone._index = index;
  80858. }
  80859. var parentBone = bone.getParent();
  80860. if (parentBone) {
  80861. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  80862. }
  80863. bones.push(bone);
  80864. };
  80865. return Skeleton;
  80866. }());
  80867. BABYLON.Skeleton = Skeleton;
  80868. })(BABYLON || (BABYLON = {}));
  80869. //# sourceMappingURL=babylon.skeleton.js.map
  80870. var BABYLON;
  80871. (function (BABYLON) {
  80872. var SphericalPolynomial = /** @class */ (function () {
  80873. function SphericalPolynomial() {
  80874. this.x = BABYLON.Vector3.Zero();
  80875. this.y = BABYLON.Vector3.Zero();
  80876. this.z = BABYLON.Vector3.Zero();
  80877. this.xx = BABYLON.Vector3.Zero();
  80878. this.yy = BABYLON.Vector3.Zero();
  80879. this.zz = BABYLON.Vector3.Zero();
  80880. this.xy = BABYLON.Vector3.Zero();
  80881. this.yz = BABYLON.Vector3.Zero();
  80882. this.zx = BABYLON.Vector3.Zero();
  80883. }
  80884. SphericalPolynomial.prototype.addAmbient = function (color) {
  80885. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80886. this.xx = this.xx.add(colorVector);
  80887. this.yy = this.yy.add(colorVector);
  80888. this.zz = this.zz.add(colorVector);
  80889. };
  80890. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  80891. var result = new SphericalPolynomial();
  80892. result.x = harmonics.L11.scale(1.02333);
  80893. result.y = harmonics.L1_1.scale(1.02333);
  80894. result.z = harmonics.L10.scale(1.02333);
  80895. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  80896. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  80897. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  80898. result.yz = harmonics.L2_1.scale(0.858086);
  80899. result.zx = harmonics.L21.scale(0.858086);
  80900. result.xy = harmonics.L2_2.scale(0.858086);
  80901. result.scale(1.0 / Math.PI);
  80902. return result;
  80903. };
  80904. SphericalPolynomial.prototype.scale = function (scale) {
  80905. this.x = this.x.scale(scale);
  80906. this.y = this.y.scale(scale);
  80907. this.z = this.z.scale(scale);
  80908. this.xx = this.xx.scale(scale);
  80909. this.yy = this.yy.scale(scale);
  80910. this.zz = this.zz.scale(scale);
  80911. this.yz = this.yz.scale(scale);
  80912. this.zx = this.zx.scale(scale);
  80913. this.xy = this.xy.scale(scale);
  80914. };
  80915. return SphericalPolynomial;
  80916. }());
  80917. BABYLON.SphericalPolynomial = SphericalPolynomial;
  80918. var SphericalHarmonics = /** @class */ (function () {
  80919. function SphericalHarmonics() {
  80920. this.L00 = BABYLON.Vector3.Zero();
  80921. this.L1_1 = BABYLON.Vector3.Zero();
  80922. this.L10 = BABYLON.Vector3.Zero();
  80923. this.L11 = BABYLON.Vector3.Zero();
  80924. this.L2_2 = BABYLON.Vector3.Zero();
  80925. this.L2_1 = BABYLON.Vector3.Zero();
  80926. this.L20 = BABYLON.Vector3.Zero();
  80927. this.L21 = BABYLON.Vector3.Zero();
  80928. this.L22 = BABYLON.Vector3.Zero();
  80929. }
  80930. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  80931. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80932. var c = colorVector.scale(deltaSolidAngle);
  80933. this.L00 = this.L00.add(c.scale(0.282095));
  80934. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  80935. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  80936. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  80937. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  80938. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  80939. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  80940. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  80941. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  80942. };
  80943. SphericalHarmonics.prototype.scale = function (scale) {
  80944. this.L00 = this.L00.scale(scale);
  80945. this.L1_1 = this.L1_1.scale(scale);
  80946. this.L10 = this.L10.scale(scale);
  80947. this.L11 = this.L11.scale(scale);
  80948. this.L2_2 = this.L2_2.scale(scale);
  80949. this.L2_1 = this.L2_1.scale(scale);
  80950. this.L20 = this.L20.scale(scale);
  80951. this.L21 = this.L21.scale(scale);
  80952. this.L22 = this.L22.scale(scale);
  80953. };
  80954. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  80955. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  80956. //
  80957. // E_lm = A_l * L_lm
  80958. //
  80959. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  80960. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  80961. // the scaling factors are given in equation 9.
  80962. // Constant (Band 0)
  80963. this.L00 = this.L00.scale(3.141593);
  80964. // Linear (Band 1)
  80965. this.L1_1 = this.L1_1.scale(2.094395);
  80966. this.L10 = this.L10.scale(2.094395);
  80967. this.L11 = this.L11.scale(2.094395);
  80968. // Quadratic (Band 2)
  80969. this.L2_2 = this.L2_2.scale(0.785398);
  80970. this.L2_1 = this.L2_1.scale(0.785398);
  80971. this.L20 = this.L20.scale(0.785398);
  80972. this.L21 = this.L21.scale(0.785398);
  80973. this.L22 = this.L22.scale(0.785398);
  80974. };
  80975. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  80976. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  80977. // L = (1/pi) * E * rho
  80978. //
  80979. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  80980. this.scale(1.0 / Math.PI);
  80981. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  80982. // (The pixel shader must apply albedo after texture fetches, etc).
  80983. };
  80984. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  80985. var result = new SphericalHarmonics();
  80986. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  80987. result.L1_1 = polynomial.y.scale(0.977204);
  80988. result.L10 = polynomial.z.scale(0.977204);
  80989. result.L11 = polynomial.x.scale(0.977204);
  80990. result.L2_2 = polynomial.xy.scale(1.16538);
  80991. result.L2_1 = polynomial.yz.scale(1.16538);
  80992. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  80993. result.L21 = polynomial.zx.scale(1.16538);
  80994. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  80995. result.scale(Math.PI);
  80996. return result;
  80997. };
  80998. return SphericalHarmonics;
  80999. }());
  81000. BABYLON.SphericalHarmonics = SphericalHarmonics;
  81001. })(BABYLON || (BABYLON = {}));
  81002. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  81003. var BABYLON;
  81004. (function (BABYLON) {
  81005. var FileFaceOrientation = /** @class */ (function () {
  81006. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  81007. this.name = name;
  81008. this.worldAxisForNormal = worldAxisForNormal;
  81009. this.worldAxisForFileX = worldAxisForFileX;
  81010. this.worldAxisForFileY = worldAxisForFileY;
  81011. }
  81012. return FileFaceOrientation;
  81013. }());
  81014. ;
  81015. /**
  81016. * Helper class dealing with the extraction of spherical polynomial dataArray
  81017. * from a cube map.
  81018. */
  81019. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  81020. function CubeMapToSphericalPolynomialTools() {
  81021. }
  81022. /**
  81023. * Converts a texture to the according Spherical Polynomial data.
  81024. * This extracts the first 3 orders only as they are the only one used in the lighting.
  81025. *
  81026. * @param texture The texture to extract the information from.
  81027. * @return The Spherical Polynomial data.
  81028. */
  81029. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  81030. if (!texture.isCube) {
  81031. // Only supports cube Textures currently.
  81032. return null;
  81033. }
  81034. var size = texture.getSize().width;
  81035. var right = texture.readPixels(0);
  81036. var left = texture.readPixels(1);
  81037. var up;
  81038. var down;
  81039. if (texture.isRenderTarget) {
  81040. up = texture.readPixels(3);
  81041. down = texture.readPixels(2);
  81042. }
  81043. else {
  81044. up = texture.readPixels(2);
  81045. down = texture.readPixels(3);
  81046. }
  81047. var front = texture.readPixels(4);
  81048. var back = texture.readPixels(5);
  81049. var gammaSpace = texture.gammaSpace;
  81050. // Always read as RGBA.
  81051. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  81052. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81053. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  81054. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81055. }
  81056. var cubeInfo = {
  81057. size: size,
  81058. right: right,
  81059. left: left,
  81060. up: up,
  81061. down: down,
  81062. front: front,
  81063. back: back,
  81064. format: format,
  81065. type: type,
  81066. gammaSpace: gammaSpace,
  81067. };
  81068. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  81069. };
  81070. /**
  81071. * Converts a cubemap to the according Spherical Polynomial data.
  81072. * This extracts the first 3 orders only as they are the only one used in the lighting.
  81073. *
  81074. * @param cubeInfo The Cube map to extract the information from.
  81075. * @return The Spherical Polynomial data.
  81076. */
  81077. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  81078. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  81079. var totalSolidAngle = 0.0;
  81080. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  81081. var du = 2.0 / cubeInfo.size;
  81082. var dv = du;
  81083. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  81084. var minUV = du * 0.5 - 1.0;
  81085. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  81086. var fileFace = this.FileFaces[faceIndex];
  81087. var dataArray = cubeInfo[fileFace.name];
  81088. var v = minUV;
  81089. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  81090. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  81091. // Because SP is still linear, so summation is fine in that basis.
  81092. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  81093. for (var y = 0; y < cubeInfo.size; y++) {
  81094. var u = minUV;
  81095. for (var x = 0; x < cubeInfo.size; x++) {
  81096. // World direction (not normalised)
  81097. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  81098. worldDirection.normalize();
  81099. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  81100. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  81101. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  81102. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  81103. // Handle Integer types.
  81104. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  81105. r /= 255;
  81106. g /= 255;
  81107. b /= 255;
  81108. }
  81109. // Handle Gamma space textures.
  81110. if (cubeInfo.gammaSpace) {
  81111. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  81112. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  81113. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  81114. }
  81115. var color = new BABYLON.Color3(r, g, b);
  81116. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  81117. totalSolidAngle += deltaSolidAngle;
  81118. u += du;
  81119. }
  81120. v += dv;
  81121. }
  81122. }
  81123. // Solid angle for entire sphere is 4*pi
  81124. var sphereSolidAngle = 4.0 * Math.PI;
  81125. // Adjust the solid angle to allow for how many faces we processed.
  81126. var facesProcessed = 6.0;
  81127. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  81128. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  81129. // This is needed because the numerical integration over the cube uses a
  81130. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  81131. // and also to compensate for accumulative error due to float precision in the summation.
  81132. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  81133. sphericalHarmonics.scale(correctionFactor);
  81134. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  81135. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  81136. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  81137. };
  81138. CubeMapToSphericalPolynomialTools.FileFaces = [
  81139. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  81140. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  81141. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  81142. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  81143. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  81144. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  81145. ];
  81146. return CubeMapToSphericalPolynomialTools;
  81147. }());
  81148. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  81149. })(BABYLON || (BABYLON = {}));
  81150. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  81151. var BABYLON;
  81152. (function (BABYLON) {
  81153. /**
  81154. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  81155. */
  81156. var PanoramaToCubeMapTools = /** @class */ (function () {
  81157. function PanoramaToCubeMapTools() {
  81158. }
  81159. /**
  81160. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  81161. *
  81162. * @param float32Array The source data.
  81163. * @param inputWidth The width of the input panorama.
  81164. * @param inputhHeight The height of the input panorama.
  81165. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  81166. * @return The cubemap data
  81167. */
  81168. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  81169. if (!float32Array) {
  81170. throw "ConvertPanoramaToCubemap: input cannot be null";
  81171. }
  81172. if (float32Array.length != inputWidth * inputHeight * 3) {
  81173. throw "ConvertPanoramaToCubemap: input size is wrong";
  81174. }
  81175. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  81176. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  81177. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  81178. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  81179. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  81180. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  81181. return {
  81182. front: textureFront,
  81183. back: textureBack,
  81184. left: textureLeft,
  81185. right: textureRight,
  81186. up: textureUp,
  81187. down: textureDown,
  81188. size: size,
  81189. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  81190. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  81191. gammaSpace: false,
  81192. };
  81193. };
  81194. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  81195. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  81196. var textureArray = new Float32Array(buffer);
  81197. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  81198. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  81199. var dy = 1 / texSize;
  81200. var fy = 0;
  81201. for (var y = 0; y < texSize; y++) {
  81202. var xv1 = faceData[0];
  81203. var xv2 = faceData[2];
  81204. for (var x = 0; x < texSize; x++) {
  81205. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  81206. v.normalize();
  81207. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  81208. // 3 channels per pixels
  81209. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  81210. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  81211. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  81212. xv1 = xv1.add(rotDX1);
  81213. xv2 = xv2.add(rotDX2);
  81214. }
  81215. fy += dy;
  81216. }
  81217. return textureArray;
  81218. };
  81219. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  81220. var theta = Math.atan2(vDir.z, vDir.x);
  81221. var phi = Math.acos(vDir.y);
  81222. while (theta < -Math.PI)
  81223. theta += 2 * Math.PI;
  81224. while (theta > Math.PI)
  81225. theta -= 2 * Math.PI;
  81226. var dx = theta / Math.PI;
  81227. var dy = phi / Math.PI;
  81228. // recenter.
  81229. dx = dx * 0.5 + 0.5;
  81230. var px = Math.round(dx * inputWidth);
  81231. if (px < 0)
  81232. px = 0;
  81233. else if (px >= inputWidth)
  81234. px = inputWidth - 1;
  81235. var py = Math.round(dy * inputHeight);
  81236. if (py < 0)
  81237. py = 0;
  81238. else if (py >= inputHeight)
  81239. py = inputHeight - 1;
  81240. var inputY = (inputHeight - py - 1);
  81241. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  81242. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  81243. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  81244. return {
  81245. r: r,
  81246. g: g,
  81247. b: b
  81248. };
  81249. };
  81250. PanoramaToCubeMapTools.FACE_FRONT = [
  81251. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  81252. new BABYLON.Vector3(1.0, -1.0, -1.0),
  81253. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  81254. new BABYLON.Vector3(1.0, 1.0, -1.0)
  81255. ];
  81256. PanoramaToCubeMapTools.FACE_BACK = [
  81257. new BABYLON.Vector3(1.0, -1.0, 1.0),
  81258. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  81259. new BABYLON.Vector3(1.0, 1.0, 1.0),
  81260. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  81261. ];
  81262. PanoramaToCubeMapTools.FACE_RIGHT = [
  81263. new BABYLON.Vector3(1.0, -1.0, -1.0),
  81264. new BABYLON.Vector3(1.0, -1.0, 1.0),
  81265. new BABYLON.Vector3(1.0, 1.0, -1.0),
  81266. new BABYLON.Vector3(1.0, 1.0, 1.0)
  81267. ];
  81268. PanoramaToCubeMapTools.FACE_LEFT = [
  81269. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  81270. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  81271. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  81272. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  81273. ];
  81274. PanoramaToCubeMapTools.FACE_DOWN = [
  81275. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  81276. new BABYLON.Vector3(1.0, 1.0, -1.0),
  81277. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  81278. new BABYLON.Vector3(1.0, 1.0, 1.0)
  81279. ];
  81280. PanoramaToCubeMapTools.FACE_UP = [
  81281. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  81282. new BABYLON.Vector3(1.0, -1.0, 1.0),
  81283. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  81284. new BABYLON.Vector3(1.0, -1.0, -1.0)
  81285. ];
  81286. return PanoramaToCubeMapTools;
  81287. }());
  81288. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  81289. })(BABYLON || (BABYLON = {}));
  81290. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  81291. var BABYLON;
  81292. (function (BABYLON) {
  81293. ;
  81294. /**
  81295. * This groups tools to convert HDR texture to native colors array.
  81296. */
  81297. var HDRTools = /** @class */ (function () {
  81298. function HDRTools() {
  81299. }
  81300. HDRTools.Ldexp = function (mantissa, exponent) {
  81301. if (exponent > 1023) {
  81302. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  81303. }
  81304. if (exponent < -1074) {
  81305. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  81306. }
  81307. return mantissa * Math.pow(2, exponent);
  81308. };
  81309. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  81310. if (exponent > 0) { /*nonzero pixel*/
  81311. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  81312. float32array[index + 0] = red * exponent;
  81313. float32array[index + 1] = green * exponent;
  81314. float32array[index + 2] = blue * exponent;
  81315. }
  81316. else {
  81317. float32array[index + 0] = 0;
  81318. float32array[index + 1] = 0;
  81319. float32array[index + 2] = 0;
  81320. }
  81321. };
  81322. HDRTools.readStringLine = function (uint8array, startIndex) {
  81323. var line = "";
  81324. var character = "";
  81325. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  81326. character = String.fromCharCode(uint8array[i]);
  81327. if (character == "\n") {
  81328. break;
  81329. }
  81330. line += character;
  81331. }
  81332. return line;
  81333. };
  81334. /**
  81335. * Reads header information from an RGBE texture stored in a native array.
  81336. * More information on this format are available here:
  81337. * https://en.wikipedia.org/wiki/RGBE_image_format
  81338. *
  81339. * @param uint8array The binary file stored in native array.
  81340. * @return The header information.
  81341. */
  81342. HDRTools.RGBE_ReadHeader = function (uint8array) {
  81343. var height = 0;
  81344. var width = 0;
  81345. var line = this.readStringLine(uint8array, 0);
  81346. if (line[0] != '#' || line[1] != '?') {
  81347. throw "Bad HDR Format.";
  81348. }
  81349. var endOfHeader = false;
  81350. var findFormat = false;
  81351. var lineIndex = 0;
  81352. do {
  81353. lineIndex += (line.length + 1);
  81354. line = this.readStringLine(uint8array, lineIndex);
  81355. if (line == "FORMAT=32-bit_rle_rgbe") {
  81356. findFormat = true;
  81357. }
  81358. else if (line.length == 0) {
  81359. endOfHeader = true;
  81360. }
  81361. } while (!endOfHeader);
  81362. if (!findFormat) {
  81363. throw "HDR Bad header format, unsupported FORMAT";
  81364. }
  81365. lineIndex += (line.length + 1);
  81366. line = this.readStringLine(uint8array, lineIndex);
  81367. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  81368. var match = sizeRegexp.exec(line);
  81369. // TODO. Support +Y and -X if needed.
  81370. if (!match || match.length < 3) {
  81371. throw "HDR Bad header format, no size";
  81372. }
  81373. width = parseInt(match[2]);
  81374. height = parseInt(match[1]);
  81375. if (width < 8 || width > 0x7fff) {
  81376. throw "HDR Bad header format, unsupported size";
  81377. }
  81378. lineIndex += (line.length + 1);
  81379. return {
  81380. height: height,
  81381. width: width,
  81382. dataPosition: lineIndex
  81383. };
  81384. };
  81385. /**
  81386. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  81387. * This RGBE texture needs to store the information as a panorama.
  81388. *
  81389. * More information on this format are available here:
  81390. * https://en.wikipedia.org/wiki/RGBE_image_format
  81391. *
  81392. * @param buffer The binary file stored in an array buffer.
  81393. * @param size The expected size of the extracted cubemap.
  81394. * @return The Cube Map information.
  81395. */
  81396. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  81397. var uint8array = new Uint8Array(buffer);
  81398. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  81399. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  81400. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  81401. return cubeMapData;
  81402. };
  81403. /**
  81404. * Returns the pixels data extracted from an RGBE texture.
  81405. * This pixels will be stored left to right up to down in the R G B order in one array.
  81406. *
  81407. * More information on this format are available here:
  81408. * https://en.wikipedia.org/wiki/RGBE_image_format
  81409. *
  81410. * @param uint8array The binary file stored in an array buffer.
  81411. * @param hdrInfo The header information of the file.
  81412. * @return The pixels data in RGB right to left up to down order.
  81413. */
  81414. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  81415. // Keep for multi format supports.
  81416. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  81417. };
  81418. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  81419. var num_scanlines = hdrInfo.height;
  81420. var scanline_width = hdrInfo.width;
  81421. var a, b, c, d, count;
  81422. var dataIndex = hdrInfo.dataPosition;
  81423. var index = 0, endIndex = 0, i = 0;
  81424. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  81425. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  81426. // 3 channels of 4 bytes per pixel in float.
  81427. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  81428. var resultArray = new Float32Array(resultBuffer);
  81429. // read in each successive scanline
  81430. while (num_scanlines > 0) {
  81431. a = uint8array[dataIndex++];
  81432. b = uint8array[dataIndex++];
  81433. c = uint8array[dataIndex++];
  81434. d = uint8array[dataIndex++];
  81435. if (a != 2 || b != 2 || (c & 0x80)) {
  81436. // this file is not run length encoded
  81437. throw "HDR Bad header format, not RLE";
  81438. }
  81439. if (((c << 8) | d) != scanline_width) {
  81440. throw "HDR Bad header format, wrong scan line width";
  81441. }
  81442. index = 0;
  81443. // read each of the four channels for the scanline into the buffer
  81444. for (i = 0; i < 4; i++) {
  81445. endIndex = (i + 1) * scanline_width;
  81446. while (index < endIndex) {
  81447. a = uint8array[dataIndex++];
  81448. b = uint8array[dataIndex++];
  81449. if (a > 128) {
  81450. // a run of the same value
  81451. count = a - 128;
  81452. if ((count == 0) || (count > endIndex - index)) {
  81453. throw "HDR Bad Format, bad scanline data (run)";
  81454. }
  81455. while (count-- > 0) {
  81456. scanLineArray[index++] = b;
  81457. }
  81458. }
  81459. else {
  81460. // a non-run
  81461. count = a;
  81462. if ((count == 0) || (count > endIndex - index)) {
  81463. throw "HDR Bad Format, bad scanline data (non-run)";
  81464. }
  81465. scanLineArray[index++] = b;
  81466. if (--count > 0) {
  81467. for (var j = 0; j < count; j++) {
  81468. scanLineArray[index++] = uint8array[dataIndex++];
  81469. }
  81470. }
  81471. }
  81472. }
  81473. }
  81474. // now convert data from buffer into floats
  81475. for (i = 0; i < scanline_width; i++) {
  81476. a = scanLineArray[i];
  81477. b = scanLineArray[i + scanline_width];
  81478. c = scanLineArray[i + 2 * scanline_width];
  81479. d = scanLineArray[i + 3 * scanline_width];
  81480. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  81481. }
  81482. num_scanlines--;
  81483. }
  81484. return resultArray;
  81485. };
  81486. return HDRTools;
  81487. }());
  81488. BABYLON.HDRTools = HDRTools;
  81489. })(BABYLON || (BABYLON = {}));
  81490. //# sourceMappingURL=babylon.hdr.js.map
  81491. var BABYLON;
  81492. (function (BABYLON) {
  81493. /**
  81494. * Sets of helpers addressing the serialization and deserialization of environment texture
  81495. * stored in a BabylonJS env file.
  81496. * Those files are usually stored as .env files.
  81497. */
  81498. var EnvironmentTextureTools = /** @class */ (function () {
  81499. function EnvironmentTextureTools() {
  81500. }
  81501. /**
  81502. * Gets the environment info from an env file.
  81503. * @param data The array buffer containing the .env bytes.
  81504. * @returns the environment file info (the json header) if successfully parsed.
  81505. */
  81506. EnvironmentTextureTools.GetEnvInfo = function (data) {
  81507. var dataView = new DataView(data);
  81508. var pos = 0;
  81509. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  81510. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  81511. BABYLON.Tools.Error('Not a babylon environment map');
  81512. return null;
  81513. }
  81514. }
  81515. // Read json manifest - collect characters up to null terminator
  81516. var manifestString = '';
  81517. var charCode = 0x00;
  81518. while ((charCode = dataView.getUint8(pos++))) {
  81519. manifestString += String.fromCharCode(charCode);
  81520. }
  81521. var manifest = JSON.parse(manifestString);
  81522. if (manifest.specular) {
  81523. // Extend the header with the position of the payload.
  81524. manifest.specular.specularDataPosition = pos;
  81525. }
  81526. return manifest;
  81527. };
  81528. /**
  81529. * Creates an environment texture from a loaded cube texture.
  81530. * @param texture defines the cube texture to convert in env file
  81531. * @return a promise containing the environment data if succesfull.
  81532. */
  81533. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  81534. var _this = this;
  81535. var internalTexture = texture.getInternalTexture();
  81536. if (!internalTexture) {
  81537. return Promise.reject("The cube texture is invalid.");
  81538. }
  81539. if (!texture._prefiltered) {
  81540. return Promise.reject("The cube texture is invalid (not prefiltered).");
  81541. }
  81542. var engine = internalTexture.getEngine();
  81543. if (engine && engine.premultipliedAlpha) {
  81544. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  81545. }
  81546. var canvas = engine.getRenderingCanvas();
  81547. if (!canvas) {
  81548. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  81549. }
  81550. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81551. if (!engine.getCaps().textureFloatRender) {
  81552. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81553. if (!engine.getCaps().textureHalfFloatRender) {
  81554. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  81555. }
  81556. }
  81557. var cubeWidth = internalTexture.width;
  81558. var hostingScene = new BABYLON.Scene(engine);
  81559. var specularTextures = {};
  81560. var promises = [];
  81561. // Read and collect all mipmaps data from the cube.
  81562. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  81563. mipmapsCount = Math.round(mipmapsCount);
  81564. var _loop_1 = function (i) {
  81565. var faceWidth = Math.pow(2, mipmapsCount - i);
  81566. var _loop_2 = function (face) {
  81567. var data = texture.readPixels(face, i);
  81568. // Creates a temp texture with the face data.
  81569. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  81570. // And rgbdEncode them.
  81571. var promise = new Promise(function (resolve, reject) {
  81572. 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);
  81573. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  81574. rgbdPostProcess.onApply = function (effect) {
  81575. effect._bindTexture("textureSampler", tempTexture);
  81576. };
  81577. // As the process needs to happen on the main canvas, keep track of the current size
  81578. var currentW = engine.getRenderWidth();
  81579. var currentH = engine.getRenderHeight();
  81580. // Set the desired size for the texture
  81581. engine.setSize(faceWidth, faceWidth);
  81582. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  81583. // Reading datas from WebGL
  81584. canvas.toBlob(function (blob) {
  81585. var fileReader = new FileReader();
  81586. fileReader.onload = function (event) {
  81587. var arrayBuffer = event.target.result;
  81588. specularTextures[i * 6 + face] = arrayBuffer;
  81589. resolve();
  81590. };
  81591. fileReader.readAsArrayBuffer(blob);
  81592. });
  81593. // Reapply the previous canvas size
  81594. engine.setSize(currentW, currentH);
  81595. });
  81596. });
  81597. promises.push(promise);
  81598. };
  81599. // All faces of the cube.
  81600. for (var face = 0; face < 6; face++) {
  81601. _loop_2(face);
  81602. }
  81603. };
  81604. for (var i = 0; i <= mipmapsCount; i++) {
  81605. _loop_1(i);
  81606. }
  81607. // Once all the textures haves been collected as RGBD stored in PNGs
  81608. return Promise.all(promises).then(function () {
  81609. // We can delete the hosting scene keeping track of all the creation objects
  81610. hostingScene.dispose();
  81611. // Creates the json header for the env texture
  81612. var info = {
  81613. version: 1,
  81614. width: cubeWidth,
  81615. irradiance: _this._CreateEnvTextureIrradiance(texture),
  81616. specular: {
  81617. mipmaps: []
  81618. }
  81619. };
  81620. // Sets the specular image data information
  81621. var position = 0;
  81622. for (var i = 0; i <= mipmapsCount; i++) {
  81623. for (var face = 0; face < 6; face++) {
  81624. var byteLength = specularTextures[i * 6 + face].byteLength;
  81625. info.specular.mipmaps.push({
  81626. length: byteLength,
  81627. position: position
  81628. });
  81629. position += byteLength;
  81630. }
  81631. }
  81632. // Encode the JSON as an array buffer
  81633. var infoString = JSON.stringify(info);
  81634. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  81635. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  81636. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  81637. infoView[i] = infoString.charCodeAt(i);
  81638. }
  81639. // Ends up with a null terminator for easier parsing
  81640. infoView[infoString.length] = 0x00;
  81641. // Computes the final required size and creates the storage
  81642. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  81643. var finalBuffer = new ArrayBuffer(totalSize);
  81644. var finalBufferView = new Uint8Array(finalBuffer);
  81645. var dataView = new DataView(finalBuffer);
  81646. // Copy the magic bytes identifying the file in
  81647. var pos = 0;
  81648. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  81649. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  81650. }
  81651. // Add the json info
  81652. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  81653. pos += infoBuffer.byteLength;
  81654. // Finally inserts the texture data
  81655. for (var i = 0; i <= mipmapsCount; i++) {
  81656. for (var face = 0; face < 6; face++) {
  81657. var dataBuffer = specularTextures[i * 6 + face];
  81658. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  81659. pos += dataBuffer.byteLength;
  81660. }
  81661. }
  81662. // Voila
  81663. return finalBuffer;
  81664. });
  81665. };
  81666. /**
  81667. * Creates a JSON representation of the spherical data.
  81668. * @param texture defines the texture containing the polynomials
  81669. * @return the JSON representation of the spherical info
  81670. */
  81671. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  81672. var polynmials = texture.sphericalPolynomial;
  81673. if (polynmials == null) {
  81674. return null;
  81675. }
  81676. return {
  81677. polynomials: true,
  81678. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  81679. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  81680. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  81681. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  81682. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  81683. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  81684. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  81685. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  81686. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  81687. };
  81688. };
  81689. /**
  81690. * Uploads the texture info contained in the env file to te GPU.
  81691. * @param texture defines the internal texture to upload to
  81692. * @param arrayBuffer defines the buffer cotaining the data to load
  81693. * @param info defines the texture info retrieved through the GetEnvInfo method
  81694. * @returns a promise
  81695. */
  81696. EnvironmentTextureTools.UploadLevelsAsync = function (texture, arrayBuffer, info) {
  81697. if (info.version !== 1) {
  81698. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  81699. }
  81700. var specularInfo = info.specular;
  81701. if (!specularInfo) {
  81702. // Nothing else parsed so far
  81703. return Promise.resolve();
  81704. }
  81705. // Double checks the enclosed info
  81706. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  81707. mipmapsCount = Math.round(mipmapsCount) + 1;
  81708. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  81709. BABYLON.Tools.Warn('Unsupported specular mipmaps number "' + specularInfo.mipmaps.length + '"');
  81710. }
  81711. // Gets everything ready.
  81712. var engine = texture.getEngine();
  81713. var expandTexture = false;
  81714. var generateNonLODTextures = false;
  81715. var rgbdPostProcess = null;
  81716. var cubeRtt = null;
  81717. var lodTextures = null;
  81718. var caps = engine.getCaps();
  81719. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  81720. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81721. texture.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  81722. // Add extra process if texture lod is not supported
  81723. if (!caps.textureLOD) {
  81724. expandTexture = false;
  81725. generateNonLODTextures = true;
  81726. lodTextures = {};
  81727. }
  81728. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  81729. else if (engine.webGLVersion < 2) {
  81730. expandTexture = false;
  81731. }
  81732. // If half float available we can uncompress the texture
  81733. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  81734. expandTexture = true;
  81735. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81736. }
  81737. // If full float available we can uncompress the texture
  81738. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  81739. expandTexture = true;
  81740. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81741. }
  81742. // Expand the texture if possible
  81743. if (expandTexture) {
  81744. // Simply run through the decode PP
  81745. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  81746. texture._isRGBD = false;
  81747. texture.invertY = false;
  81748. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  81749. generateDepthBuffer: false,
  81750. generateMipMaps: true,
  81751. generateStencilBuffer: false,
  81752. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  81753. type: texture.type,
  81754. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  81755. });
  81756. }
  81757. else {
  81758. texture._isRGBD = true;
  81759. texture.invertY = true;
  81760. // In case of missing support, applies the same patch than DDS files.
  81761. if (generateNonLODTextures) {
  81762. var mipSlices = 3;
  81763. var scale = texture._lodGenerationScale;
  81764. var offset = texture._lodGenerationOffset;
  81765. for (var i = 0; i < mipSlices; i++) {
  81766. //compute LOD from even spacing in smoothness (matching shader calculation)
  81767. var smoothness = i / (mipSlices - 1);
  81768. var roughness = 1 - smoothness;
  81769. var minLODIndex = offset; // roughness = 0
  81770. var maxLODIndex = BABYLON.Scalar.Log2(info.width) * scale + offset; // roughness = 1
  81771. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  81772. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  81773. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  81774. glTextureFromLod.isCube = true;
  81775. glTextureFromLod.invertY = true;
  81776. glTextureFromLod.generateMipMaps = false;
  81777. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  81778. // Wrap in a base texture for easy binding.
  81779. var lodTexture = new BABYLON.BaseTexture(null);
  81780. lodTexture.isCube = true;
  81781. lodTexture._texture = glTextureFromLod;
  81782. lodTextures[mipmapIndex] = lodTexture;
  81783. switch (i) {
  81784. case 0:
  81785. texture._lodTextureLow = lodTexture;
  81786. break;
  81787. case 1:
  81788. texture._lodTextureMid = lodTexture;
  81789. break;
  81790. case 2:
  81791. texture._lodTextureHigh = lodTexture;
  81792. break;
  81793. }
  81794. }
  81795. }
  81796. }
  81797. var promises = [];
  81798. var _loop_3 = function (i) {
  81799. var _loop_4 = function (face) {
  81800. // Retrieves the face data
  81801. var imageData = specularInfo.mipmaps[i * 6 + face];
  81802. var bytes = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageData.position, imageData.length);
  81803. // Constructs an image element from bytes
  81804. var blob = new Blob([bytes], { type: 'image/png' });
  81805. var url = URL.createObjectURL(blob);
  81806. var image = new Image();
  81807. image.src = url;
  81808. // Enqueue promise to upload to the texture.
  81809. var promise = new Promise(function (resolve, reject) {
  81810. ;
  81811. image.onload = function () {
  81812. if (expandTexture) {
  81813. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  81814. reject(message);
  81815. }, image);
  81816. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  81817. // Uncompress the data to a RTT
  81818. rgbdPostProcess.onApply = function (effect) {
  81819. effect._bindTexture("textureSampler", tempTexture_1);
  81820. effect.setFloat2("scale", 1, 1);
  81821. };
  81822. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  81823. // Cleanup
  81824. engine.restoreDefaultFramebuffer();
  81825. tempTexture_1.dispose();
  81826. window.URL.revokeObjectURL(url);
  81827. resolve();
  81828. });
  81829. }
  81830. else {
  81831. engine._uploadImageToTexture(texture, face, i, image);
  81832. // Upload the face to the none lod texture support
  81833. if (generateNonLODTextures) {
  81834. var lodTexture = lodTextures[i];
  81835. if (lodTexture) {
  81836. engine._uploadImageToTexture(lodTexture._texture, face, 0, image);
  81837. }
  81838. }
  81839. resolve();
  81840. }
  81841. };
  81842. image.onerror = function (error) {
  81843. reject(error);
  81844. };
  81845. });
  81846. promises.push(promise);
  81847. };
  81848. // All faces
  81849. for (var face = 0; face < 6; face++) {
  81850. _loop_4(face);
  81851. }
  81852. };
  81853. // All mipmaps
  81854. for (var i = 0; i < mipmapsCount; i++) {
  81855. _loop_3(i);
  81856. }
  81857. // Once all done, finishes the cleanup and return
  81858. return Promise.all(promises).then(function () {
  81859. // Relase temp RTT.
  81860. if (cubeRtt) {
  81861. engine._releaseFramebufferObjects(cubeRtt);
  81862. cubeRtt._swapAndDie(texture);
  81863. }
  81864. // Relase temp Post Process.
  81865. if (rgbdPostProcess) {
  81866. rgbdPostProcess.dispose();
  81867. }
  81868. // Flag internal texture as ready in case they are in use.
  81869. if (generateNonLODTextures) {
  81870. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  81871. texture._lodTextureHigh._texture.isReady = true;
  81872. }
  81873. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  81874. texture._lodTextureMid._texture.isReady = true;
  81875. }
  81876. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  81877. texture._lodTextureLow._texture.isReady = true;
  81878. }
  81879. }
  81880. });
  81881. };
  81882. /**
  81883. * Uploads spherical polynomials information to the texture.
  81884. * @param texture defines the texture we are trying to upload the information to
  81885. * @param arrayBuffer defines the array buffer holding the data
  81886. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  81887. */
  81888. EnvironmentTextureTools.UploadPolynomials = function (texture, arrayBuffer, info) {
  81889. if (info.version !== 1) {
  81890. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  81891. }
  81892. var irradianceInfo = info.irradiance;
  81893. if (!irradianceInfo) {
  81894. return;
  81895. }
  81896. //harmonics now represent radiance
  81897. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  81898. if (irradianceInfo.polynomials) {
  81899. EnvironmentTextureTools._UploadSP(irradianceInfo, texture._sphericalPolynomial);
  81900. }
  81901. else {
  81902. // convert From SH to SP.
  81903. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance(irradianceInfo);
  81904. EnvironmentTextureTools._ConvertSHToSP(irradianceInfo, texture._sphericalPolynomial);
  81905. }
  81906. };
  81907. /**
  81908. * Upload spherical polynomial coefficients to the texture
  81909. * @param polynmials Spherical polynmial coefficients (9)
  81910. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  81911. */
  81912. EnvironmentTextureTools._UploadSP = function (polynmials, outPolynomialCoefficents) {
  81913. outPolynomialCoefficents.x.x = polynmials.x[0];
  81914. outPolynomialCoefficents.x.y = polynmials.x[1];
  81915. outPolynomialCoefficents.x.z = polynmials.x[2];
  81916. outPolynomialCoefficents.y.x = polynmials.y[0];
  81917. outPolynomialCoefficents.y.y = polynmials.y[1];
  81918. outPolynomialCoefficents.y.z = polynmials.y[2];
  81919. outPolynomialCoefficents.z.x = polynmials.z[0];
  81920. outPolynomialCoefficents.z.y = polynmials.z[1];
  81921. outPolynomialCoefficents.z.z = polynmials.z[2];
  81922. //xx
  81923. outPolynomialCoefficents.xx.x = polynmials.xx[0];
  81924. outPolynomialCoefficents.xx.y = polynmials.xx[1];
  81925. outPolynomialCoefficents.xx.z = polynmials.xx[2];
  81926. outPolynomialCoefficents.yy.x = polynmials.yy[0];
  81927. outPolynomialCoefficents.yy.y = polynmials.yy[1];
  81928. outPolynomialCoefficents.yy.z = polynmials.yy[2];
  81929. outPolynomialCoefficents.zz.x = polynmials.zz[0];
  81930. outPolynomialCoefficents.zz.y = polynmials.zz[1];
  81931. outPolynomialCoefficents.zz.z = polynmials.zz[2];
  81932. //yz
  81933. outPolynomialCoefficents.yz.x = polynmials.yz[0];
  81934. outPolynomialCoefficents.yz.y = polynmials.yz[1];
  81935. outPolynomialCoefficents.yz.z = polynmials.yz[2];
  81936. outPolynomialCoefficents.zx.x = polynmials.zx[0];
  81937. outPolynomialCoefficents.zx.y = polynmials.zx[1];
  81938. outPolynomialCoefficents.zx.z = polynmials.zx[2];
  81939. outPolynomialCoefficents.xy.x = polynmials.xy[0];
  81940. outPolynomialCoefficents.xy.y = polynmials.xy[1];
  81941. outPolynomialCoefficents.xy.z = polynmials.xy[2];
  81942. };
  81943. /**
  81944. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  81945. * L = (1/pi) * E * rho
  81946. *
  81947. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  81948. * @param harmonics Spherical harmonic coefficients (9)
  81949. */
  81950. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  81951. var scaleFactor = 1 / Math.PI;
  81952. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  81953. // (The pixel shader must apply albedo after texture fetches, etc).
  81954. harmonics.l00[0] *= scaleFactor;
  81955. harmonics.l00[1] *= scaleFactor;
  81956. harmonics.l00[2] *= scaleFactor;
  81957. harmonics.l1_1[0] *= scaleFactor;
  81958. harmonics.l1_1[1] *= scaleFactor;
  81959. harmonics.l1_1[2] *= scaleFactor;
  81960. harmonics.l10[0] *= scaleFactor;
  81961. harmonics.l10[1] *= scaleFactor;
  81962. harmonics.l10[2] *= scaleFactor;
  81963. harmonics.l11[0] *= scaleFactor;
  81964. harmonics.l11[1] *= scaleFactor;
  81965. harmonics.l11[2] *= scaleFactor;
  81966. harmonics.l2_2[0] *= scaleFactor;
  81967. harmonics.l2_2[1] *= scaleFactor;
  81968. harmonics.l2_2[2] *= scaleFactor;
  81969. harmonics.l2_1[0] *= scaleFactor;
  81970. harmonics.l2_1[1] *= scaleFactor;
  81971. harmonics.l2_1[2] *= scaleFactor;
  81972. harmonics.l20[0] *= scaleFactor;
  81973. harmonics.l20[1] *= scaleFactor;
  81974. harmonics.l20[2] *= scaleFactor;
  81975. harmonics.l21[0] *= scaleFactor;
  81976. harmonics.l21[1] *= scaleFactor;
  81977. harmonics.l21[2] *= scaleFactor;
  81978. harmonics.l22[0] *= scaleFactor;
  81979. harmonics.l22[1] *= scaleFactor;
  81980. harmonics.l22[2] *= scaleFactor;
  81981. };
  81982. /**
  81983. * Convert spherical harmonics to spherical polynomial coefficients
  81984. * @param harmonics Spherical harmonic coefficients (9)
  81985. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  81986. */
  81987. EnvironmentTextureTools._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  81988. var rPi = 1 / Math.PI;
  81989. //x
  81990. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  81991. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  81992. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  81993. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  81994. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  81995. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  81996. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  81997. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  81998. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  81999. //xx
  82000. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  82001. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  82002. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  82003. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  82004. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  82005. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  82006. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  82007. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  82008. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  82009. //yz
  82010. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  82011. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  82012. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  82013. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  82014. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  82015. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  82016. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  82017. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  82018. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  82019. };
  82020. /**
  82021. * Magic number identifying the env file.
  82022. */
  82023. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  82024. return EnvironmentTextureTools;
  82025. }());
  82026. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  82027. })(BABYLON || (BABYLON = {}));
  82028. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  82029. var BABYLON;
  82030. (function (BABYLON) {
  82031. /**
  82032. * This represents a texture coming from an HDR input.
  82033. *
  82034. * The only supported format is currently panorama picture stored in RGBE format.
  82035. * Example of such files can be found on HDRLib: http://hdrlib.com/
  82036. */
  82037. var HDRCubeTexture = /** @class */ (function (_super) {
  82038. __extends(HDRCubeTexture, _super);
  82039. /**
  82040. * Instantiates an HDRTexture from the following parameters.
  82041. *
  82042. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  82043. * @param scene The scene the texture will be used in
  82044. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  82045. * @param noMipmap Forces to not generate the mipmap if true
  82046. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  82047. * @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)
  82048. * @param reserved Reserved flag for internal use.
  82049. */
  82050. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  82051. if (noMipmap === void 0) { noMipmap = false; }
  82052. if (generateHarmonics === void 0) { generateHarmonics = true; }
  82053. if (gammaSpace === void 0) { gammaSpace = false; }
  82054. if (reserved === void 0) { reserved = false; }
  82055. if (onLoad === void 0) { onLoad = null; }
  82056. if (onError === void 0) { onError = null; }
  82057. var _this = _super.call(this, scene) || this;
  82058. _this._generateHarmonics = true;
  82059. _this._onLoad = null;
  82060. _this._onError = null;
  82061. /**
  82062. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  82063. */
  82064. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  82065. _this._isBlocking = true;
  82066. _this._rotationY = 0;
  82067. /**
  82068. * Gets or sets the center of the bounding box associated with the cube texture
  82069. * It must define where the camera used to render the texture was set
  82070. */
  82071. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  82072. if (!url) {
  82073. return _this;
  82074. }
  82075. _this.name = url;
  82076. _this.url = url;
  82077. _this.hasAlpha = false;
  82078. _this.isCube = true;
  82079. _this._textureMatrix = BABYLON.Matrix.Identity();
  82080. _this._onLoad = onLoad;
  82081. _this._onError = onError;
  82082. _this.gammaSpace = gammaSpace;
  82083. _this._noMipmap = noMipmap;
  82084. _this._size = size;
  82085. _this._texture = _this._getFromCache(url, _this._noMipmap);
  82086. if (!_this._texture) {
  82087. if (!scene.useDelayedTextureLoading) {
  82088. _this.loadTexture();
  82089. }
  82090. else {
  82091. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  82092. }
  82093. }
  82094. return _this;
  82095. }
  82096. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  82097. /**
  82098. * Gets wether or not the texture is blocking during loading.
  82099. */
  82100. get: function () {
  82101. return this._isBlocking;
  82102. },
  82103. /**
  82104. * Sets wether or not the texture is blocking during loading.
  82105. */
  82106. set: function (value) {
  82107. this._isBlocking = value;
  82108. },
  82109. enumerable: true,
  82110. configurable: true
  82111. });
  82112. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  82113. /**
  82114. * Gets texture matrix rotation angle around Y axis radians.
  82115. */
  82116. get: function () {
  82117. return this._rotationY;
  82118. },
  82119. /**
  82120. * Sets texture matrix rotation angle around Y axis in radians.
  82121. */
  82122. set: function (value) {
  82123. this._rotationY = value;
  82124. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  82125. },
  82126. enumerable: true,
  82127. configurable: true
  82128. });
  82129. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  82130. get: function () {
  82131. return this._boundingBoxSize;
  82132. },
  82133. /**
  82134. * Gets or sets the size of the bounding box associated with the cube texture
  82135. * When defined, the cubemap will switch to local mode
  82136. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  82137. * @example https://www.babylonjs-playground.com/#RNASML
  82138. */
  82139. set: function (value) {
  82140. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  82141. return;
  82142. }
  82143. this._boundingBoxSize = value;
  82144. var scene = this.getScene();
  82145. if (scene) {
  82146. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  82147. }
  82148. },
  82149. enumerable: true,
  82150. configurable: true
  82151. });
  82152. /**
  82153. * Occurs when the file is raw .hdr file.
  82154. */
  82155. HDRCubeTexture.prototype.loadTexture = function () {
  82156. var _this = this;
  82157. var callback = function (buffer) {
  82158. _this.lodGenerationOffset = 0.0;
  82159. _this.lodGenerationScale = 0.8;
  82160. var scene = _this.getScene();
  82161. if (!scene) {
  82162. return null;
  82163. }
  82164. // Extract the raw linear data.
  82165. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  82166. // Generate harmonics if needed.
  82167. if (_this._generateHarmonics) {
  82168. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  82169. _this.sphericalPolynomial = sphericalPolynomial;
  82170. }
  82171. var results = [];
  82172. var byteArray = null;
  82173. // Push each faces.
  82174. for (var j = 0; j < 6; j++) {
  82175. // Create uintarray fallback.
  82176. if (!scene.getEngine().getCaps().textureFloat) {
  82177. // 3 channels of 1 bytes per pixel in bytes.
  82178. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  82179. byteArray = new Uint8Array(byteBuffer);
  82180. }
  82181. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  82182. // If special cases.
  82183. if (_this.gammaSpace || byteArray) {
  82184. for (var i = 0; i < _this._size * _this._size; i++) {
  82185. // Put in gamma space if requested.
  82186. if (_this.gammaSpace) {
  82187. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  82188. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  82189. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  82190. }
  82191. // Convert to int texture for fallback.
  82192. if (byteArray) {
  82193. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  82194. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  82195. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  82196. // May use luminance instead if the result is not accurate.
  82197. var max = Math.max(Math.max(r, g), b);
  82198. if (max > 255) {
  82199. var scale = 255 / max;
  82200. r *= scale;
  82201. g *= scale;
  82202. b *= scale;
  82203. }
  82204. byteArray[(i * 3) + 0] = r;
  82205. byteArray[(i * 3) + 1] = g;
  82206. byteArray[(i * 3) + 2] = b;
  82207. }
  82208. }
  82209. }
  82210. if (byteArray) {
  82211. results.push(byteArray);
  82212. }
  82213. else {
  82214. results.push(dataFace);
  82215. }
  82216. }
  82217. return results;
  82218. };
  82219. var scene = this.getScene();
  82220. if (scene) {
  82221. 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);
  82222. }
  82223. };
  82224. HDRCubeTexture.prototype.clone = function () {
  82225. var scene = this.getScene();
  82226. if (!scene) {
  82227. return this;
  82228. }
  82229. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  82230. // Base texture
  82231. newTexture.level = this.level;
  82232. newTexture.wrapU = this.wrapU;
  82233. newTexture.wrapV = this.wrapV;
  82234. newTexture.coordinatesIndex = this.coordinatesIndex;
  82235. newTexture.coordinatesMode = this.coordinatesMode;
  82236. return newTexture;
  82237. };
  82238. // Methods
  82239. HDRCubeTexture.prototype.delayLoad = function () {
  82240. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  82241. return;
  82242. }
  82243. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  82244. this._texture = this._getFromCache(this.url, this._noMipmap);
  82245. if (!this._texture) {
  82246. this.loadTexture();
  82247. }
  82248. };
  82249. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  82250. return this._textureMatrix;
  82251. };
  82252. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  82253. this._textureMatrix = value;
  82254. };
  82255. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  82256. var texture = null;
  82257. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  82258. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  82259. texture.name = parsedTexture.name;
  82260. texture.hasAlpha = parsedTexture.hasAlpha;
  82261. texture.level = parsedTexture.level;
  82262. texture.coordinatesMode = parsedTexture.coordinatesMode;
  82263. texture.isBlocking = parsedTexture.isBlocking;
  82264. }
  82265. if (texture) {
  82266. if (parsedTexture.boundingBoxPosition) {
  82267. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  82268. }
  82269. if (parsedTexture.boundingBoxSize) {
  82270. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  82271. }
  82272. if (parsedTexture.rotationY) {
  82273. texture.rotationY = parsedTexture.rotationY;
  82274. }
  82275. }
  82276. return texture;
  82277. };
  82278. HDRCubeTexture.prototype.serialize = function () {
  82279. if (!this.name) {
  82280. return null;
  82281. }
  82282. var serializationObject = {};
  82283. serializationObject.name = this.name;
  82284. serializationObject.hasAlpha = this.hasAlpha;
  82285. serializationObject.isCube = true;
  82286. serializationObject.level = this.level;
  82287. serializationObject.size = this._size;
  82288. serializationObject.coordinatesMode = this.coordinatesMode;
  82289. serializationObject.useInGammaSpace = this.gammaSpace;
  82290. serializationObject.generateHarmonics = this._generateHarmonics;
  82291. serializationObject.customType = "BABYLON.HDRCubeTexture";
  82292. serializationObject.noMipmap = this._noMipmap;
  82293. serializationObject.isBlocking = this._isBlocking;
  82294. serializationObject.rotationY = this._rotationY;
  82295. return serializationObject;
  82296. };
  82297. HDRCubeTexture._facesMapping = [
  82298. "right",
  82299. "left",
  82300. "up",
  82301. "down",
  82302. "front",
  82303. "back"
  82304. ];
  82305. return HDRCubeTexture;
  82306. }(BABYLON.BaseTexture));
  82307. BABYLON.HDRCubeTexture = HDRCubeTexture;
  82308. })(BABYLON || (BABYLON = {}));
  82309. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  82310. var BABYLON;
  82311. (function (BABYLON) {
  82312. var IndexedVector2 = /** @class */ (function (_super) {
  82313. __extends(IndexedVector2, _super);
  82314. function IndexedVector2(original, index) {
  82315. var _this = _super.call(this, original.x, original.y) || this;
  82316. _this.index = index;
  82317. return _this;
  82318. }
  82319. return IndexedVector2;
  82320. }(BABYLON.Vector2));
  82321. var PolygonPoints = /** @class */ (function () {
  82322. function PolygonPoints() {
  82323. this.elements = new Array();
  82324. }
  82325. PolygonPoints.prototype.add = function (originalPoints) {
  82326. var _this = this;
  82327. var result = new Array();
  82328. originalPoints.forEach(function (point) {
  82329. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  82330. var newPoint = new IndexedVector2(point, _this.elements.length);
  82331. result.push(newPoint);
  82332. _this.elements.push(newPoint);
  82333. }
  82334. });
  82335. return result;
  82336. };
  82337. PolygonPoints.prototype.computeBounds = function () {
  82338. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  82339. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  82340. this.elements.forEach(function (point) {
  82341. // x
  82342. if (point.x < lmin.x) {
  82343. lmin.x = point.x;
  82344. }
  82345. else if (point.x > lmax.x) {
  82346. lmax.x = point.x;
  82347. }
  82348. // y
  82349. if (point.y < lmin.y) {
  82350. lmin.y = point.y;
  82351. }
  82352. else if (point.y > lmax.y) {
  82353. lmax.y = point.y;
  82354. }
  82355. });
  82356. return {
  82357. min: lmin,
  82358. max: lmax,
  82359. width: lmax.x - lmin.x,
  82360. height: lmax.y - lmin.y
  82361. };
  82362. };
  82363. return PolygonPoints;
  82364. }());
  82365. var Polygon = /** @class */ (function () {
  82366. function Polygon() {
  82367. }
  82368. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  82369. return [
  82370. new BABYLON.Vector2(xmin, ymin),
  82371. new BABYLON.Vector2(xmax, ymin),
  82372. new BABYLON.Vector2(xmax, ymax),
  82373. new BABYLON.Vector2(xmin, ymax)
  82374. ];
  82375. };
  82376. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  82377. if (cx === void 0) { cx = 0; }
  82378. if (cy === void 0) { cy = 0; }
  82379. if (numberOfSides === void 0) { numberOfSides = 32; }
  82380. var result = new Array();
  82381. var angle = 0;
  82382. var increment = (Math.PI * 2) / numberOfSides;
  82383. for (var i = 0; i < numberOfSides; i++) {
  82384. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  82385. angle -= increment;
  82386. }
  82387. return result;
  82388. };
  82389. Polygon.Parse = function (input) {
  82390. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  82391. var i, result = [];
  82392. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  82393. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  82394. }
  82395. return result;
  82396. };
  82397. Polygon.StartingAt = function (x, y) {
  82398. return BABYLON.Path2.StartingAt(x, y);
  82399. };
  82400. return Polygon;
  82401. }());
  82402. BABYLON.Polygon = Polygon;
  82403. var PolygonMeshBuilder = /** @class */ (function () {
  82404. function PolygonMeshBuilder(name, contours, scene) {
  82405. this._points = new PolygonPoints();
  82406. this._outlinepoints = new PolygonPoints();
  82407. this._holes = new Array();
  82408. this._epoints = new Array();
  82409. this._eholes = new Array();
  82410. this._name = name;
  82411. this._scene = scene;
  82412. var points;
  82413. if (contours instanceof BABYLON.Path2) {
  82414. points = contours.getPoints();
  82415. }
  82416. else {
  82417. points = contours;
  82418. }
  82419. this._addToepoint(points);
  82420. this._points.add(points);
  82421. this._outlinepoints.add(points);
  82422. if (typeof earcut === 'undefined') {
  82423. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  82424. }
  82425. }
  82426. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  82427. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  82428. var p = points_1[_i];
  82429. this._epoints.push(p.x, p.y);
  82430. }
  82431. };
  82432. PolygonMeshBuilder.prototype.addHole = function (hole) {
  82433. this._points.add(hole);
  82434. var holepoints = new PolygonPoints();
  82435. holepoints.add(hole);
  82436. this._holes.push(holepoints);
  82437. this._eholes.push(this._epoints.length / 2);
  82438. this._addToepoint(hole);
  82439. return this;
  82440. };
  82441. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  82442. var _this = this;
  82443. if (updatable === void 0) { updatable = false; }
  82444. if (depth === void 0) { depth = 0; }
  82445. var result = new BABYLON.Mesh(this._name, this._scene);
  82446. var normals = new Array();
  82447. var positions = new Array();
  82448. var uvs = new Array();
  82449. var bounds = this._points.computeBounds();
  82450. this._points.elements.forEach(function (p) {
  82451. normals.push(0, 1.0, 0);
  82452. positions.push(p.x, 0, p.y);
  82453. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  82454. });
  82455. var indices = new Array();
  82456. var res = earcut(this._epoints, this._eholes, 2);
  82457. for (var i = 0; i < res.length; i++) {
  82458. indices.push(res[i]);
  82459. }
  82460. if (depth > 0) {
  82461. var positionscount = (positions.length / 3); //get the current pointcount
  82462. this._points.elements.forEach(function (p) {
  82463. normals.push(0, -1.0, 0);
  82464. positions.push(p.x, -depth, p.y);
  82465. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  82466. });
  82467. var totalCount = indices.length;
  82468. for (var i = 0; i < totalCount; i += 3) {
  82469. var i0 = indices[i + 0];
  82470. var i1 = indices[i + 1];
  82471. var i2 = indices[i + 2];
  82472. indices.push(i2 + positionscount);
  82473. indices.push(i1 + positionscount);
  82474. indices.push(i0 + positionscount);
  82475. }
  82476. //Add the sides
  82477. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  82478. this._holes.forEach(function (hole) {
  82479. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  82480. });
  82481. }
  82482. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  82483. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  82484. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  82485. result.setIndices(indices);
  82486. return result;
  82487. };
  82488. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  82489. var StartIndex = positions.length / 3;
  82490. var ulength = 0;
  82491. for (var i = 0; i < points.elements.length; i++) {
  82492. var p = points.elements[i];
  82493. var p1;
  82494. if ((i + 1) > points.elements.length - 1) {
  82495. p1 = points.elements[0];
  82496. }
  82497. else {
  82498. p1 = points.elements[i + 1];
  82499. }
  82500. positions.push(p.x, 0, p.y);
  82501. positions.push(p.x, -depth, p.y);
  82502. positions.push(p1.x, 0, p1.y);
  82503. positions.push(p1.x, -depth, p1.y);
  82504. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  82505. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  82506. var v3 = v2.subtract(v1);
  82507. var v4 = new BABYLON.Vector3(0, 1, 0);
  82508. var vn = BABYLON.Vector3.Cross(v3, v4);
  82509. vn = vn.normalize();
  82510. uvs.push(ulength / bounds.width, 0);
  82511. uvs.push(ulength / bounds.width, 1);
  82512. ulength += v3.length();
  82513. uvs.push((ulength / bounds.width), 0);
  82514. uvs.push((ulength / bounds.width), 1);
  82515. if (!flip) {
  82516. normals.push(-vn.x, -vn.y, -vn.z);
  82517. normals.push(-vn.x, -vn.y, -vn.z);
  82518. normals.push(-vn.x, -vn.y, -vn.z);
  82519. normals.push(-vn.x, -vn.y, -vn.z);
  82520. indices.push(StartIndex);
  82521. indices.push(StartIndex + 1);
  82522. indices.push(StartIndex + 2);
  82523. indices.push(StartIndex + 1);
  82524. indices.push(StartIndex + 3);
  82525. indices.push(StartIndex + 2);
  82526. }
  82527. else {
  82528. normals.push(vn.x, vn.y, vn.z);
  82529. normals.push(vn.x, vn.y, vn.z);
  82530. normals.push(vn.x, vn.y, vn.z);
  82531. normals.push(vn.x, vn.y, vn.z);
  82532. indices.push(StartIndex);
  82533. indices.push(StartIndex + 2);
  82534. indices.push(StartIndex + 1);
  82535. indices.push(StartIndex + 1);
  82536. indices.push(StartIndex + 2);
  82537. indices.push(StartIndex + 3);
  82538. }
  82539. StartIndex += 4;
  82540. }
  82541. ;
  82542. };
  82543. return PolygonMeshBuilder;
  82544. }());
  82545. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  82546. })(BABYLON || (BABYLON = {}));
  82547. //# sourceMappingURL=babylon.polygonMesh.js.map
  82548. var BABYLON;
  82549. (function (BABYLON) {
  82550. // Unique ID when we import meshes from Babylon to CSG
  82551. var currentCSGMeshId = 0;
  82552. // # class Vertex
  82553. // Represents a vertex of a polygon. Use your own vertex class instead of this
  82554. // one to provide additional features like texture coordinates and vertex
  82555. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  82556. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  82557. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  82558. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  82559. // is not used anywhere else.
  82560. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  82561. var Vertex = /** @class */ (function () {
  82562. function Vertex(pos, normal, uv) {
  82563. this.pos = pos;
  82564. this.normal = normal;
  82565. this.uv = uv;
  82566. }
  82567. Vertex.prototype.clone = function () {
  82568. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  82569. };
  82570. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  82571. // orientation of a polygon is flipped.
  82572. Vertex.prototype.flip = function () {
  82573. this.normal = this.normal.scale(-1);
  82574. };
  82575. // Create a new vertex between this vertex and `other` by linearly
  82576. // interpolating all properties using a parameter of `t`. Subclasses should
  82577. // override this to interpolate additional properties.
  82578. Vertex.prototype.interpolate = function (other, t) {
  82579. 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));
  82580. };
  82581. return Vertex;
  82582. }());
  82583. // # class Plane
  82584. // Represents a plane in 3D space.
  82585. var Plane = /** @class */ (function () {
  82586. function Plane(normal, w) {
  82587. this.normal = normal;
  82588. this.w = w;
  82589. }
  82590. Plane.FromPoints = function (a, b, c) {
  82591. var v0 = c.subtract(a);
  82592. var v1 = b.subtract(a);
  82593. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  82594. return null;
  82595. }
  82596. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  82597. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  82598. };
  82599. Plane.prototype.clone = function () {
  82600. return new Plane(this.normal.clone(), this.w);
  82601. };
  82602. Plane.prototype.flip = function () {
  82603. this.normal.scaleInPlace(-1);
  82604. this.w = -this.w;
  82605. };
  82606. // Split `polygon` by this plane if needed, then put the polygon or polygon
  82607. // fragments in the appropriate lists. Coplanar polygons go into either
  82608. // `coplanarFront` or `coplanarBack` depending on their orientation with
  82609. // respect to this plane. Polygons in front or in back of this plane go into
  82610. // either `front` or `back`.
  82611. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  82612. var COPLANAR = 0;
  82613. var FRONT = 1;
  82614. var BACK = 2;
  82615. var SPANNING = 3;
  82616. // Classify each point as well as the entire polygon into one of the above
  82617. // four classes.
  82618. var polygonType = 0;
  82619. var types = [];
  82620. var i;
  82621. var t;
  82622. for (i = 0; i < polygon.vertices.length; i++) {
  82623. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  82624. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  82625. polygonType |= type;
  82626. types.push(type);
  82627. }
  82628. // Put the polygon in the correct list, splitting it when necessary.
  82629. switch (polygonType) {
  82630. case COPLANAR:
  82631. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  82632. break;
  82633. case FRONT:
  82634. front.push(polygon);
  82635. break;
  82636. case BACK:
  82637. back.push(polygon);
  82638. break;
  82639. case SPANNING:
  82640. var f = [], b = [];
  82641. for (i = 0; i < polygon.vertices.length; i++) {
  82642. var j = (i + 1) % polygon.vertices.length;
  82643. var ti = types[i], tj = types[j];
  82644. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  82645. if (ti !== BACK)
  82646. f.push(vi);
  82647. if (ti !== FRONT)
  82648. b.push(ti !== BACK ? vi.clone() : vi);
  82649. if ((ti | tj) === SPANNING) {
  82650. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  82651. var v = vi.interpolate(vj, t);
  82652. f.push(v);
  82653. b.push(v.clone());
  82654. }
  82655. }
  82656. var poly;
  82657. if (f.length >= 3) {
  82658. poly = new Polygon(f, polygon.shared);
  82659. if (poly.plane)
  82660. front.push(poly);
  82661. }
  82662. if (b.length >= 3) {
  82663. poly = new Polygon(b, polygon.shared);
  82664. if (poly.plane)
  82665. back.push(poly);
  82666. }
  82667. break;
  82668. }
  82669. };
  82670. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  82671. // point is on the plane.
  82672. Plane.EPSILON = 1e-5;
  82673. return Plane;
  82674. }());
  82675. // # class Polygon
  82676. // Represents a convex polygon. The vertices used to initialize a polygon must
  82677. // be coplanar and form a convex loop.
  82678. //
  82679. // Each convex polygon has a `shared` property, which is shared between all
  82680. // polygons that are clones of each other or were split from the same polygon.
  82681. // This can be used to define per-polygon properties (such as surface color).
  82682. var Polygon = /** @class */ (function () {
  82683. function Polygon(vertices, shared) {
  82684. this.vertices = vertices;
  82685. this.shared = shared;
  82686. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  82687. }
  82688. Polygon.prototype.clone = function () {
  82689. var vertices = this.vertices.map(function (v) { return v.clone(); });
  82690. return new Polygon(vertices, this.shared);
  82691. };
  82692. Polygon.prototype.flip = function () {
  82693. this.vertices.reverse().map(function (v) { v.flip(); });
  82694. this.plane.flip();
  82695. };
  82696. return Polygon;
  82697. }());
  82698. // # class Node
  82699. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  82700. // by picking a polygon to split along. That polygon (and all other coplanar
  82701. // polygons) are added directly to that node and the other polygons are added to
  82702. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  82703. // no distinction between internal and leaf nodes.
  82704. var Node = /** @class */ (function () {
  82705. function Node(polygons) {
  82706. this.plane = null;
  82707. this.front = null;
  82708. this.back = null;
  82709. this.polygons = new Array();
  82710. if (polygons) {
  82711. this.build(polygons);
  82712. }
  82713. }
  82714. Node.prototype.clone = function () {
  82715. var node = new Node();
  82716. node.plane = this.plane && this.plane.clone();
  82717. node.front = this.front && this.front.clone();
  82718. node.back = this.back && this.back.clone();
  82719. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  82720. return node;
  82721. };
  82722. // Convert solid space to empty space and empty space to solid space.
  82723. Node.prototype.invert = function () {
  82724. for (var i = 0; i < this.polygons.length; i++) {
  82725. this.polygons[i].flip();
  82726. }
  82727. if (this.plane) {
  82728. this.plane.flip();
  82729. }
  82730. if (this.front) {
  82731. this.front.invert();
  82732. }
  82733. if (this.back) {
  82734. this.back.invert();
  82735. }
  82736. var temp = this.front;
  82737. this.front = this.back;
  82738. this.back = temp;
  82739. };
  82740. // Recursively remove all polygons in `polygons` that are inside this BSP
  82741. // tree.
  82742. Node.prototype.clipPolygons = function (polygons) {
  82743. if (!this.plane)
  82744. return polygons.slice();
  82745. var front = new Array(), back = new Array();
  82746. for (var i = 0; i < polygons.length; i++) {
  82747. this.plane.splitPolygon(polygons[i], front, back, front, back);
  82748. }
  82749. if (this.front) {
  82750. front = this.front.clipPolygons(front);
  82751. }
  82752. if (this.back) {
  82753. back = this.back.clipPolygons(back);
  82754. }
  82755. else {
  82756. back = [];
  82757. }
  82758. return front.concat(back);
  82759. };
  82760. // Remove all polygons in this BSP tree that are inside the other BSP tree
  82761. // `bsp`.
  82762. Node.prototype.clipTo = function (bsp) {
  82763. this.polygons = bsp.clipPolygons(this.polygons);
  82764. if (this.front)
  82765. this.front.clipTo(bsp);
  82766. if (this.back)
  82767. this.back.clipTo(bsp);
  82768. };
  82769. // Return a list of all polygons in this BSP tree.
  82770. Node.prototype.allPolygons = function () {
  82771. var polygons = this.polygons.slice();
  82772. if (this.front)
  82773. polygons = polygons.concat(this.front.allPolygons());
  82774. if (this.back)
  82775. polygons = polygons.concat(this.back.allPolygons());
  82776. return polygons;
  82777. };
  82778. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  82779. // new polygons are filtered down to the bottom of the tree and become new
  82780. // nodes there. Each set of polygons is partitioned using the first polygon
  82781. // (no heuristic is used to pick a good split).
  82782. Node.prototype.build = function (polygons) {
  82783. if (!polygons.length)
  82784. return;
  82785. if (!this.plane)
  82786. this.plane = polygons[0].plane.clone();
  82787. var front = new Array(), back = new Array();
  82788. for (var i = 0; i < polygons.length; i++) {
  82789. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  82790. }
  82791. if (front.length) {
  82792. if (!this.front)
  82793. this.front = new Node();
  82794. this.front.build(front);
  82795. }
  82796. if (back.length) {
  82797. if (!this.back)
  82798. this.back = new Node();
  82799. this.back.build(back);
  82800. }
  82801. };
  82802. return Node;
  82803. }());
  82804. var CSG = /** @class */ (function () {
  82805. function CSG() {
  82806. this.polygons = new Array();
  82807. }
  82808. // Convert BABYLON.Mesh to BABYLON.CSG
  82809. CSG.FromMesh = function (mesh) {
  82810. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  82811. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  82812. if (mesh instanceof BABYLON.Mesh) {
  82813. mesh.computeWorldMatrix(true);
  82814. matrix = mesh.getWorldMatrix();
  82815. meshPosition = mesh.position.clone();
  82816. meshRotation = mesh.rotation.clone();
  82817. if (mesh.rotationQuaternion) {
  82818. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  82819. }
  82820. meshScaling = mesh.scaling.clone();
  82821. }
  82822. else {
  82823. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  82824. }
  82825. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  82826. var subMeshes = mesh.subMeshes;
  82827. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  82828. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  82829. vertices = [];
  82830. for (var j = 0; j < 3; j++) {
  82831. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  82832. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  82833. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  82834. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  82835. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  82836. vertex = new Vertex(position, normal, uv);
  82837. vertices.push(vertex);
  82838. }
  82839. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  82840. // To handle the case of degenerated triangle
  82841. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  82842. if (polygon.plane)
  82843. polygons.push(polygon);
  82844. }
  82845. }
  82846. var csg = CSG.FromPolygons(polygons);
  82847. csg.matrix = matrix;
  82848. csg.position = meshPosition;
  82849. csg.rotation = meshRotation;
  82850. csg.scaling = meshScaling;
  82851. csg.rotationQuaternion = meshRotationQuaternion;
  82852. currentCSGMeshId++;
  82853. return csg;
  82854. };
  82855. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  82856. CSG.FromPolygons = function (polygons) {
  82857. var csg = new CSG();
  82858. csg.polygons = polygons;
  82859. return csg;
  82860. };
  82861. CSG.prototype.clone = function () {
  82862. var csg = new CSG();
  82863. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  82864. csg.copyTransformAttributes(this);
  82865. return csg;
  82866. };
  82867. CSG.prototype.union = function (csg) {
  82868. var a = new Node(this.clone().polygons);
  82869. var b = new Node(csg.clone().polygons);
  82870. a.clipTo(b);
  82871. b.clipTo(a);
  82872. b.invert();
  82873. b.clipTo(a);
  82874. b.invert();
  82875. a.build(b.allPolygons());
  82876. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  82877. };
  82878. CSG.prototype.unionInPlace = function (csg) {
  82879. var a = new Node(this.polygons);
  82880. var b = new Node(csg.polygons);
  82881. a.clipTo(b);
  82882. b.clipTo(a);
  82883. b.invert();
  82884. b.clipTo(a);
  82885. b.invert();
  82886. a.build(b.allPolygons());
  82887. this.polygons = a.allPolygons();
  82888. };
  82889. CSG.prototype.subtract = function (csg) {
  82890. var a = new Node(this.clone().polygons);
  82891. var b = new Node(csg.clone().polygons);
  82892. a.invert();
  82893. a.clipTo(b);
  82894. b.clipTo(a);
  82895. b.invert();
  82896. b.clipTo(a);
  82897. b.invert();
  82898. a.build(b.allPolygons());
  82899. a.invert();
  82900. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  82901. };
  82902. CSG.prototype.subtractInPlace = function (csg) {
  82903. var a = new Node(this.polygons);
  82904. var b = new Node(csg.polygons);
  82905. a.invert();
  82906. a.clipTo(b);
  82907. b.clipTo(a);
  82908. b.invert();
  82909. b.clipTo(a);
  82910. b.invert();
  82911. a.build(b.allPolygons());
  82912. a.invert();
  82913. this.polygons = a.allPolygons();
  82914. };
  82915. CSG.prototype.intersect = function (csg) {
  82916. var a = new Node(this.clone().polygons);
  82917. var b = new Node(csg.clone().polygons);
  82918. a.invert();
  82919. b.clipTo(a);
  82920. b.invert();
  82921. a.clipTo(b);
  82922. b.clipTo(a);
  82923. a.build(b.allPolygons());
  82924. a.invert();
  82925. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  82926. };
  82927. CSG.prototype.intersectInPlace = function (csg) {
  82928. var a = new Node(this.polygons);
  82929. var b = new Node(csg.polygons);
  82930. a.invert();
  82931. b.clipTo(a);
  82932. b.invert();
  82933. a.clipTo(b);
  82934. b.clipTo(a);
  82935. a.build(b.allPolygons());
  82936. a.invert();
  82937. this.polygons = a.allPolygons();
  82938. };
  82939. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  82940. // not modified.
  82941. CSG.prototype.inverse = function () {
  82942. var csg = this.clone();
  82943. csg.inverseInPlace();
  82944. return csg;
  82945. };
  82946. CSG.prototype.inverseInPlace = function () {
  82947. this.polygons.map(function (p) { p.flip(); });
  82948. };
  82949. // This is used to keep meshes transformations so they can be restored
  82950. // when we build back a Babylon Mesh
  82951. // NB : All CSG operations are performed in world coordinates
  82952. CSG.prototype.copyTransformAttributes = function (csg) {
  82953. this.matrix = csg.matrix;
  82954. this.position = csg.position;
  82955. this.rotation = csg.rotation;
  82956. this.scaling = csg.scaling;
  82957. this.rotationQuaternion = csg.rotationQuaternion;
  82958. return this;
  82959. };
  82960. // Build Raw mesh from CSG
  82961. // Coordinates here are in world space
  82962. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  82963. var matrix = this.matrix.clone();
  82964. matrix.invert();
  82965. 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;
  82966. if (keepSubMeshes) {
  82967. // Sort Polygons, since subMeshes are indices range
  82968. polygons.sort(function (a, b) {
  82969. if (a.shared.meshId === b.shared.meshId) {
  82970. return a.shared.subMeshId - b.shared.subMeshId;
  82971. }
  82972. else {
  82973. return a.shared.meshId - b.shared.meshId;
  82974. }
  82975. });
  82976. }
  82977. for (var i = 0, il = polygons.length; i < il; i++) {
  82978. polygon = polygons[i];
  82979. // Building SubMeshes
  82980. if (!subMesh_dict[polygon.shared.meshId]) {
  82981. subMesh_dict[polygon.shared.meshId] = {};
  82982. }
  82983. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  82984. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  82985. indexStart: +Infinity,
  82986. indexEnd: -Infinity,
  82987. materialIndex: polygon.shared.materialIndex
  82988. };
  82989. }
  82990. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  82991. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  82992. polygonIndices[0] = 0;
  82993. polygonIndices[1] = j - 1;
  82994. polygonIndices[2] = j;
  82995. for (var k = 0; k < 3; k++) {
  82996. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  82997. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  82998. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  82999. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  83000. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  83001. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  83002. // Check if 2 points can be merged
  83003. if (!(typeof vertex_idx !== 'undefined' &&
  83004. normals[vertex_idx * 3] === localNormal.x &&
  83005. normals[vertex_idx * 3 + 1] === localNormal.y &&
  83006. normals[vertex_idx * 3 + 2] === localNormal.z &&
  83007. uvs[vertex_idx * 2] === uv.x &&
  83008. uvs[vertex_idx * 2 + 1] === uv.y)) {
  83009. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  83010. uvs.push(uv.x, uv.y);
  83011. normals.push(normal.x, normal.y, normal.z);
  83012. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  83013. }
  83014. indices.push(vertex_idx);
  83015. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  83016. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  83017. currentIndex++;
  83018. }
  83019. }
  83020. }
  83021. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  83022. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  83023. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  83024. mesh.setIndices(indices, null);
  83025. if (keepSubMeshes) {
  83026. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  83027. var materialIndexOffset = 0, materialMaxIndex;
  83028. mesh.subMeshes = new Array();
  83029. for (var m in subMesh_dict) {
  83030. materialMaxIndex = -1;
  83031. for (var sm in subMesh_dict[m]) {
  83032. subMesh_obj = subMesh_dict[m][sm];
  83033. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  83034. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  83035. }
  83036. materialIndexOffset += ++materialMaxIndex;
  83037. }
  83038. }
  83039. return mesh;
  83040. };
  83041. // Build Mesh from CSG taking material and transforms into account
  83042. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  83043. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  83044. mesh.material = material;
  83045. mesh.position.copyFrom(this.position);
  83046. mesh.rotation.copyFrom(this.rotation);
  83047. if (this.rotationQuaternion) {
  83048. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  83049. }
  83050. mesh.scaling.copyFrom(this.scaling);
  83051. mesh.computeWorldMatrix(true);
  83052. return mesh;
  83053. };
  83054. return CSG;
  83055. }());
  83056. BABYLON.CSG = CSG;
  83057. })(BABYLON || (BABYLON = {}));
  83058. //# sourceMappingURL=babylon.csg.js.map
  83059. var BABYLON;
  83060. (function (BABYLON) {
  83061. var LensFlare = /** @class */ (function () {
  83062. function LensFlare(size, position, color, imgUrl, system) {
  83063. this.size = size;
  83064. this.position = position;
  83065. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  83066. this.color = color || new BABYLON.Color3(1, 1, 1);
  83067. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  83068. this._system = system;
  83069. system.lensFlares.push(this);
  83070. }
  83071. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  83072. return new LensFlare(size, position, color, imgUrl, system);
  83073. };
  83074. LensFlare.prototype.dispose = function () {
  83075. if (this.texture) {
  83076. this.texture.dispose();
  83077. }
  83078. // Remove from scene
  83079. var index = this._system.lensFlares.indexOf(this);
  83080. this._system.lensFlares.splice(index, 1);
  83081. };
  83082. ;
  83083. return LensFlare;
  83084. }());
  83085. BABYLON.LensFlare = LensFlare;
  83086. })(BABYLON || (BABYLON = {}));
  83087. //# sourceMappingURL=babylon.lensFlare.js.map
  83088. var BABYLON;
  83089. (function (BABYLON) {
  83090. var LensFlareSystem = /** @class */ (function () {
  83091. function LensFlareSystem(name, emitter, scene) {
  83092. this.name = name;
  83093. this.lensFlares = new Array();
  83094. this.borderLimit = 300;
  83095. this.viewportBorder = 0;
  83096. this.layerMask = 0x0FFFFFFF;
  83097. this._vertexBuffers = {};
  83098. this._isEnabled = true;
  83099. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83100. this._emitter = emitter;
  83101. this.id = name;
  83102. scene.lensFlareSystems.push(this);
  83103. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  83104. var engine = scene.getEngine();
  83105. // VBO
  83106. var vertices = [];
  83107. vertices.push(1, 1);
  83108. vertices.push(-1, 1);
  83109. vertices.push(-1, -1);
  83110. vertices.push(1, -1);
  83111. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  83112. // Indices
  83113. var indices = [];
  83114. indices.push(0);
  83115. indices.push(1);
  83116. indices.push(2);
  83117. indices.push(0);
  83118. indices.push(2);
  83119. indices.push(3);
  83120. this._indexBuffer = engine.createIndexBuffer(indices);
  83121. // Effects
  83122. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  83123. }
  83124. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  83125. get: function () {
  83126. return this._isEnabled;
  83127. },
  83128. set: function (value) {
  83129. this._isEnabled = value;
  83130. },
  83131. enumerable: true,
  83132. configurable: true
  83133. });
  83134. LensFlareSystem.prototype.getScene = function () {
  83135. return this._scene;
  83136. };
  83137. LensFlareSystem.prototype.getEmitter = function () {
  83138. return this._emitter;
  83139. };
  83140. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  83141. this._emitter = newEmitter;
  83142. };
  83143. LensFlareSystem.prototype.getEmitterPosition = function () {
  83144. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  83145. };
  83146. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  83147. var position = this.getEmitterPosition();
  83148. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  83149. this._positionX = position.x;
  83150. this._positionY = position.y;
  83151. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  83152. if (this.viewportBorder > 0) {
  83153. globalViewport.x -= this.viewportBorder;
  83154. globalViewport.y -= this.viewportBorder;
  83155. globalViewport.width += this.viewportBorder * 2;
  83156. globalViewport.height += this.viewportBorder * 2;
  83157. position.x += this.viewportBorder;
  83158. position.y += this.viewportBorder;
  83159. this._positionX += this.viewportBorder;
  83160. this._positionY += this.viewportBorder;
  83161. }
  83162. if (position.z > 0) {
  83163. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  83164. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  83165. return true;
  83166. }
  83167. return true;
  83168. }
  83169. return false;
  83170. };
  83171. LensFlareSystem.prototype._isVisible = function () {
  83172. if (!this._isEnabled || !this._scene.activeCamera) {
  83173. return false;
  83174. }
  83175. var emitterPosition = this.getEmitterPosition();
  83176. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  83177. var distance = direction.length();
  83178. direction.normalize();
  83179. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  83180. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  83181. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  83182. };
  83183. LensFlareSystem.prototype.render = function () {
  83184. if (!this._effect.isReady() || !this._scene.activeCamera)
  83185. return false;
  83186. var engine = this._scene.getEngine();
  83187. var viewport = this._scene.activeCamera.viewport;
  83188. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  83189. // Position
  83190. if (!this.computeEffectivePosition(globalViewport)) {
  83191. return false;
  83192. }
  83193. // Visibility
  83194. if (!this._isVisible()) {
  83195. return false;
  83196. }
  83197. // Intensity
  83198. var awayX;
  83199. var awayY;
  83200. if (this._positionX < this.borderLimit + globalViewport.x) {
  83201. awayX = this.borderLimit + globalViewport.x - this._positionX;
  83202. }
  83203. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  83204. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  83205. }
  83206. else {
  83207. awayX = 0;
  83208. }
  83209. if (this._positionY < this.borderLimit + globalViewport.y) {
  83210. awayY = this.borderLimit + globalViewport.y - this._positionY;
  83211. }
  83212. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  83213. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  83214. }
  83215. else {
  83216. awayY = 0;
  83217. }
  83218. var away = (awayX > awayY) ? awayX : awayY;
  83219. away -= this.viewportBorder;
  83220. if (away > this.borderLimit) {
  83221. away = this.borderLimit;
  83222. }
  83223. var intensity = 1.0 - (away / this.borderLimit);
  83224. if (intensity < 0) {
  83225. return false;
  83226. }
  83227. if (intensity > 1.0) {
  83228. intensity = 1.0;
  83229. }
  83230. if (this.viewportBorder > 0) {
  83231. globalViewport.x += this.viewportBorder;
  83232. globalViewport.y += this.viewportBorder;
  83233. globalViewport.width -= this.viewportBorder * 2;
  83234. globalViewport.height -= this.viewportBorder * 2;
  83235. this._positionX -= this.viewportBorder;
  83236. this._positionY -= this.viewportBorder;
  83237. }
  83238. // Position
  83239. var centerX = globalViewport.x + globalViewport.width / 2;
  83240. var centerY = globalViewport.y + globalViewport.height / 2;
  83241. var distX = centerX - this._positionX;
  83242. var distY = centerY - this._positionY;
  83243. // Effects
  83244. engine.enableEffect(this._effect);
  83245. engine.setState(false);
  83246. engine.setDepthBuffer(false);
  83247. // VBOs
  83248. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  83249. // Flares
  83250. for (var index = 0; index < this.lensFlares.length; index++) {
  83251. var flare = this.lensFlares[index];
  83252. engine.setAlphaMode(flare.alphaMode);
  83253. var x = centerX - (distX * flare.position);
  83254. var y = centerY - (distY * flare.position);
  83255. var cw = flare.size;
  83256. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  83257. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  83258. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  83259. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  83260. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  83261. // Texture
  83262. this._effect.setTexture("textureSampler", flare.texture);
  83263. // Color
  83264. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  83265. // Draw order
  83266. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83267. }
  83268. engine.setDepthBuffer(true);
  83269. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  83270. return true;
  83271. };
  83272. LensFlareSystem.prototype.dispose = function () {
  83273. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83274. if (vertexBuffer) {
  83275. vertexBuffer.dispose();
  83276. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  83277. }
  83278. if (this._indexBuffer) {
  83279. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  83280. this._indexBuffer = null;
  83281. }
  83282. while (this.lensFlares.length) {
  83283. this.lensFlares[0].dispose();
  83284. }
  83285. // Remove from scene
  83286. var index = this._scene.lensFlareSystems.indexOf(this);
  83287. this._scene.lensFlareSystems.splice(index, 1);
  83288. };
  83289. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  83290. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  83291. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  83292. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  83293. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  83294. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  83295. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  83296. var parsedFlare = parsedLensFlareSystem.flares[index];
  83297. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  83298. }
  83299. return lensFlareSystem;
  83300. };
  83301. LensFlareSystem.prototype.serialize = function () {
  83302. var serializationObject = {};
  83303. serializationObject.id = this.id;
  83304. serializationObject.name = this.name;
  83305. serializationObject.emitterId = this.getEmitter().id;
  83306. serializationObject.borderLimit = this.borderLimit;
  83307. serializationObject.flares = [];
  83308. for (var index = 0; index < this.lensFlares.length; index++) {
  83309. var flare = this.lensFlares[index];
  83310. serializationObject.flares.push({
  83311. size: flare.size,
  83312. position: flare.position,
  83313. color: flare.color.asArray(),
  83314. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  83315. });
  83316. }
  83317. return serializationObject;
  83318. };
  83319. return LensFlareSystem;
  83320. }());
  83321. BABYLON.LensFlareSystem = LensFlareSystem;
  83322. })(BABYLON || (BABYLON = {}));
  83323. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  83324. var BABYLON;
  83325. (function (BABYLON) {
  83326. /**
  83327. * This is a holder class for the physics joint created by the physics plugin.
  83328. * It holds a set of functions to control the underlying joint.
  83329. */
  83330. var PhysicsJoint = /** @class */ (function () {
  83331. function PhysicsJoint(type, jointData) {
  83332. this.type = type;
  83333. this.jointData = jointData;
  83334. jointData.nativeParams = jointData.nativeParams || {};
  83335. }
  83336. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  83337. get: function () {
  83338. return this._physicsJoint;
  83339. },
  83340. set: function (newJoint) {
  83341. if (this._physicsJoint) {
  83342. //remove from the wolrd
  83343. }
  83344. this._physicsJoint = newJoint;
  83345. },
  83346. enumerable: true,
  83347. configurable: true
  83348. });
  83349. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  83350. set: function (physicsPlugin) {
  83351. this._physicsPlugin = physicsPlugin;
  83352. },
  83353. enumerable: true,
  83354. configurable: true
  83355. });
  83356. /**
  83357. * Execute a function that is physics-plugin specific.
  83358. * @param {Function} func the function that will be executed.
  83359. * It accepts two parameters: the physics world and the physics joint.
  83360. */
  83361. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  83362. func(this._physicsPlugin.world, this._physicsJoint);
  83363. };
  83364. //TODO check if the native joints are the same
  83365. //Joint Types
  83366. PhysicsJoint.DistanceJoint = 0;
  83367. PhysicsJoint.HingeJoint = 1;
  83368. PhysicsJoint.BallAndSocketJoint = 2;
  83369. PhysicsJoint.WheelJoint = 3;
  83370. PhysicsJoint.SliderJoint = 4;
  83371. //OIMO
  83372. PhysicsJoint.PrismaticJoint = 5;
  83373. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  83374. PhysicsJoint.UniversalJoint = 6;
  83375. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  83376. //Cannon
  83377. //Similar to a Ball-Joint. Different in params
  83378. PhysicsJoint.PointToPointJoint = 8;
  83379. //Cannon only at the moment
  83380. PhysicsJoint.SpringJoint = 9;
  83381. PhysicsJoint.LockJoint = 10;
  83382. return PhysicsJoint;
  83383. }());
  83384. BABYLON.PhysicsJoint = PhysicsJoint;
  83385. /**
  83386. * A class representing a physics distance joint.
  83387. */
  83388. var DistanceJoint = /** @class */ (function (_super) {
  83389. __extends(DistanceJoint, _super);
  83390. function DistanceJoint(jointData) {
  83391. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  83392. }
  83393. /**
  83394. * Update the predefined distance.
  83395. */
  83396. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  83397. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  83398. };
  83399. return DistanceJoint;
  83400. }(PhysicsJoint));
  83401. BABYLON.DistanceJoint = DistanceJoint;
  83402. var MotorEnabledJoint = /** @class */ (function (_super) {
  83403. __extends(MotorEnabledJoint, _super);
  83404. function MotorEnabledJoint(type, jointData) {
  83405. return _super.call(this, type, jointData) || this;
  83406. }
  83407. /**
  83408. * Set the motor values.
  83409. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83410. * @param {number} force the force to apply
  83411. * @param {number} maxForce max force for this motor.
  83412. */
  83413. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  83414. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  83415. };
  83416. /**
  83417. * Set the motor's limits.
  83418. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83419. */
  83420. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  83421. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  83422. };
  83423. return MotorEnabledJoint;
  83424. }(PhysicsJoint));
  83425. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  83426. /**
  83427. * This class represents a single hinge physics joint
  83428. */
  83429. var HingeJoint = /** @class */ (function (_super) {
  83430. __extends(HingeJoint, _super);
  83431. function HingeJoint(jointData) {
  83432. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  83433. }
  83434. /**
  83435. * Set the motor values.
  83436. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83437. * @param {number} force the force to apply
  83438. * @param {number} maxForce max force for this motor.
  83439. */
  83440. HingeJoint.prototype.setMotor = function (force, maxForce) {
  83441. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  83442. };
  83443. /**
  83444. * Set the motor's limits.
  83445. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83446. */
  83447. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  83448. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  83449. };
  83450. return HingeJoint;
  83451. }(MotorEnabledJoint));
  83452. BABYLON.HingeJoint = HingeJoint;
  83453. /**
  83454. * This class represents a dual hinge physics joint (same as wheel joint)
  83455. */
  83456. var Hinge2Joint = /** @class */ (function (_super) {
  83457. __extends(Hinge2Joint, _super);
  83458. function Hinge2Joint(jointData) {
  83459. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  83460. }
  83461. /**
  83462. * Set the motor values.
  83463. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83464. * @param {number} force the force to apply
  83465. * @param {number} maxForce max force for this motor.
  83466. * @param {motorIndex} the motor's index, 0 or 1.
  83467. */
  83468. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  83469. if (motorIndex === void 0) { motorIndex = 0; }
  83470. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  83471. };
  83472. /**
  83473. * Set the motor limits.
  83474. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83475. * @param {number} upperLimit the upper limit
  83476. * @param {number} lowerLimit lower limit
  83477. * @param {motorIndex} the motor's index, 0 or 1.
  83478. */
  83479. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  83480. if (motorIndex === void 0) { motorIndex = 0; }
  83481. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  83482. };
  83483. return Hinge2Joint;
  83484. }(MotorEnabledJoint));
  83485. BABYLON.Hinge2Joint = Hinge2Joint;
  83486. })(BABYLON || (BABYLON = {}));
  83487. //# sourceMappingURL=babylon.physicsJoint.js.map
  83488. var BABYLON;
  83489. (function (BABYLON) {
  83490. var PhysicsImpostor = /** @class */ (function () {
  83491. function PhysicsImpostor(object, type, _options, _scene) {
  83492. if (_options === void 0) { _options = { mass: 0 }; }
  83493. var _this = this;
  83494. this.object = object;
  83495. this.type = type;
  83496. this._options = _options;
  83497. this._scene = _scene;
  83498. this._bodyUpdateRequired = false;
  83499. this._onBeforePhysicsStepCallbacks = new Array();
  83500. this._onAfterPhysicsStepCallbacks = new Array();
  83501. this._onPhysicsCollideCallbacks = [];
  83502. this._deltaPosition = BABYLON.Vector3.Zero();
  83503. this._isDisposed = false;
  83504. //temp variables for parent rotation calculations
  83505. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  83506. this._tmpQuat = new BABYLON.Quaternion();
  83507. this._tmpQuat2 = new BABYLON.Quaternion();
  83508. /**
  83509. * this function is executed by the physics engine.
  83510. */
  83511. this.beforeStep = function () {
  83512. if (!_this._physicsEngine) {
  83513. return;
  83514. }
  83515. _this.object.translate(_this._deltaPosition, -1);
  83516. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  83517. _this.object.computeWorldMatrix(false);
  83518. if (_this.object.parent && _this.object.rotationQuaternion) {
  83519. _this.getParentsRotation();
  83520. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  83521. }
  83522. else {
  83523. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  83524. }
  83525. if (!_this._options.disableBidirectionalTransformation) {
  83526. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  83527. }
  83528. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  83529. func(_this);
  83530. });
  83531. };
  83532. /**
  83533. * this function is executed by the physics engine.
  83534. */
  83535. this.afterStep = function () {
  83536. if (!_this._physicsEngine) {
  83537. return;
  83538. }
  83539. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  83540. func(_this);
  83541. });
  83542. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  83543. // object has now its world rotation. needs to be converted to local.
  83544. if (_this.object.parent && _this.object.rotationQuaternion) {
  83545. _this.getParentsRotation();
  83546. _this._tmpQuat.conjugateInPlace();
  83547. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  83548. }
  83549. // take the position set and make it the absolute position of this object.
  83550. _this.object.setAbsolutePosition(_this.object.position);
  83551. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  83552. _this.object.translate(_this._deltaPosition, 1);
  83553. };
  83554. /**
  83555. * Legacy collision detection event support
  83556. */
  83557. this.onCollideEvent = null;
  83558. //event and body object due to cannon's event-based architecture.
  83559. this.onCollide = function (e) {
  83560. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  83561. return;
  83562. }
  83563. if (!_this._physicsEngine) {
  83564. return;
  83565. }
  83566. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  83567. if (otherImpostor) {
  83568. // Legacy collision detection event support
  83569. if (_this.onCollideEvent) {
  83570. _this.onCollideEvent(_this, otherImpostor);
  83571. }
  83572. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  83573. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  83574. }).forEach(function (obj) {
  83575. obj.callback(_this, otherImpostor);
  83576. });
  83577. }
  83578. };
  83579. //sanity check!
  83580. if (!this.object) {
  83581. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  83582. return;
  83583. }
  83584. //legacy support for old syntax.
  83585. if (!this._scene && object.getScene) {
  83586. this._scene = object.getScene();
  83587. }
  83588. if (!this._scene) {
  83589. return;
  83590. }
  83591. this._physicsEngine = this._scene.getPhysicsEngine();
  83592. if (!this._physicsEngine) {
  83593. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  83594. }
  83595. else {
  83596. //set the object's quaternion, if not set
  83597. if (!this.object.rotationQuaternion) {
  83598. if (this.object.rotation) {
  83599. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  83600. }
  83601. else {
  83602. this.object.rotationQuaternion = new BABYLON.Quaternion();
  83603. }
  83604. }
  83605. //default options params
  83606. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  83607. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  83608. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  83609. this._joints = [];
  83610. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  83611. if (!this.object.parent || this._options.ignoreParent) {
  83612. this._init();
  83613. }
  83614. else if (this.object.parent.physicsImpostor) {
  83615. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  83616. }
  83617. }
  83618. }
  83619. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  83620. get: function () {
  83621. return this._isDisposed;
  83622. },
  83623. enumerable: true,
  83624. configurable: true
  83625. });
  83626. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  83627. get: function () {
  83628. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  83629. },
  83630. set: function (value) {
  83631. this.setMass(value);
  83632. },
  83633. enumerable: true,
  83634. configurable: true
  83635. });
  83636. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  83637. get: function () {
  83638. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  83639. },
  83640. set: function (value) {
  83641. if (!this._physicsEngine) {
  83642. return;
  83643. }
  83644. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  83645. },
  83646. enumerable: true,
  83647. configurable: true
  83648. });
  83649. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  83650. get: function () {
  83651. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  83652. },
  83653. set: function (value) {
  83654. if (!this._physicsEngine) {
  83655. return;
  83656. }
  83657. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  83658. },
  83659. enumerable: true,
  83660. configurable: true
  83661. });
  83662. /**
  83663. * This function will completly initialize this impostor.
  83664. * It will create a new body - but only if this mesh has no parent.
  83665. * If it has, this impostor will not be used other than to define the impostor
  83666. * of the child mesh.
  83667. */
  83668. PhysicsImpostor.prototype._init = function () {
  83669. if (!this._physicsEngine) {
  83670. return;
  83671. }
  83672. this._physicsEngine.removeImpostor(this);
  83673. this.physicsBody = null;
  83674. this._parent = this._parent || this._getPhysicsParent();
  83675. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  83676. this._physicsEngine.addImpostor(this);
  83677. }
  83678. };
  83679. PhysicsImpostor.prototype._getPhysicsParent = function () {
  83680. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  83681. var parentMesh = this.object.parent;
  83682. return parentMesh.physicsImpostor;
  83683. }
  83684. return null;
  83685. };
  83686. /**
  83687. * Should a new body be generated.
  83688. */
  83689. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  83690. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  83691. };
  83692. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  83693. this.forceUpdate();
  83694. };
  83695. /**
  83696. * Force a regeneration of this or the parent's impostor's body.
  83697. * Use under cautious - This will remove all joints already implemented.
  83698. */
  83699. PhysicsImpostor.prototype.forceUpdate = function () {
  83700. this._init();
  83701. if (this.parent && !this._options.ignoreParent) {
  83702. this.parent.forceUpdate();
  83703. }
  83704. };
  83705. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  83706. /*public get mesh(): AbstractMesh {
  83707. return this._mesh;
  83708. }*/
  83709. /**
  83710. * Gets the body that holds this impostor. Either its own, or its parent.
  83711. */
  83712. get: function () {
  83713. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  83714. },
  83715. /**
  83716. * Set the physics body. Used mainly by the physics engine/plugin
  83717. */
  83718. set: function (physicsBody) {
  83719. if (this._physicsBody && this._physicsEngine) {
  83720. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  83721. }
  83722. this._physicsBody = physicsBody;
  83723. this.resetUpdateFlags();
  83724. },
  83725. enumerable: true,
  83726. configurable: true
  83727. });
  83728. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  83729. get: function () {
  83730. return !this._options.ignoreParent && this._parent ? this._parent : null;
  83731. },
  83732. set: function (value) {
  83733. this._parent = value;
  83734. },
  83735. enumerable: true,
  83736. configurable: true
  83737. });
  83738. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  83739. this._bodyUpdateRequired = false;
  83740. };
  83741. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  83742. if (this.object.getBoundingInfo) {
  83743. var q = this.object.rotationQuaternion;
  83744. //reset rotation
  83745. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  83746. //calculate the world matrix with no rotation
  83747. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  83748. var boundingInfo = this.object.getBoundingInfo();
  83749. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  83750. //bring back the rotation
  83751. this.object.rotationQuaternion = q;
  83752. //calculate the world matrix with the new rotation
  83753. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  83754. return size;
  83755. }
  83756. else {
  83757. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  83758. }
  83759. };
  83760. PhysicsImpostor.prototype.getObjectCenter = function () {
  83761. if (this.object.getBoundingInfo) {
  83762. var boundingInfo = this.object.getBoundingInfo();
  83763. return boundingInfo.boundingBox.centerWorld;
  83764. }
  83765. else {
  83766. return this.object.position;
  83767. }
  83768. };
  83769. /**
  83770. * Get a specific parametes from the options parameter.
  83771. */
  83772. PhysicsImpostor.prototype.getParam = function (paramName) {
  83773. return this._options[paramName];
  83774. };
  83775. /**
  83776. * Sets a specific parameter in the options given to the physics plugin
  83777. */
  83778. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  83779. this._options[paramName] = value;
  83780. this._bodyUpdateRequired = true;
  83781. };
  83782. /**
  83783. * Specifically change the body's mass option. Won't recreate the physics body object
  83784. */
  83785. PhysicsImpostor.prototype.setMass = function (mass) {
  83786. if (this.getParam("mass") !== mass) {
  83787. this.setParam("mass", mass);
  83788. }
  83789. if (this._physicsEngine) {
  83790. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  83791. }
  83792. };
  83793. PhysicsImpostor.prototype.getLinearVelocity = function () {
  83794. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  83795. };
  83796. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  83797. if (this._physicsEngine) {
  83798. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  83799. }
  83800. };
  83801. PhysicsImpostor.prototype.getAngularVelocity = function () {
  83802. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  83803. };
  83804. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  83805. if (this._physicsEngine) {
  83806. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  83807. }
  83808. };
  83809. /**
  83810. * Execute a function with the physics plugin native code.
  83811. * Provide a function the will have two variables - the world object and the physics body object.
  83812. */
  83813. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  83814. if (this._physicsEngine) {
  83815. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  83816. }
  83817. };
  83818. /**
  83819. * Register a function that will be executed before the physics world is stepping forward.
  83820. */
  83821. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  83822. this._onBeforePhysicsStepCallbacks.push(func);
  83823. };
  83824. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  83825. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  83826. if (index > -1) {
  83827. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  83828. }
  83829. else {
  83830. BABYLON.Tools.Warn("Function to remove was not found");
  83831. }
  83832. };
  83833. /**
  83834. * Register a function that will be executed after the physics step
  83835. */
  83836. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  83837. this._onAfterPhysicsStepCallbacks.push(func);
  83838. };
  83839. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  83840. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  83841. if (index > -1) {
  83842. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  83843. }
  83844. else {
  83845. BABYLON.Tools.Warn("Function to remove was not found");
  83846. }
  83847. };
  83848. /**
  83849. * register a function that will be executed when this impostor collides against a different body.
  83850. */
  83851. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  83852. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  83853. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  83854. };
  83855. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  83856. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  83857. var index = -1;
  83858. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  83859. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  83860. // chcek the arrays match
  83861. var sameList = cbDef.otherImpostors.every(function (impostor) {
  83862. return collidedAgainstList.indexOf(impostor) > -1;
  83863. });
  83864. if (sameList) {
  83865. index = idx;
  83866. }
  83867. return sameList;
  83868. }
  83869. return false;
  83870. });
  83871. if (found) {
  83872. this._onPhysicsCollideCallbacks.splice(index, 1);
  83873. }
  83874. else {
  83875. BABYLON.Tools.Warn("Function to remove was not found");
  83876. }
  83877. };
  83878. PhysicsImpostor.prototype.getParentsRotation = function () {
  83879. var parent = this.object.parent;
  83880. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  83881. while (parent) {
  83882. if (parent.rotationQuaternion) {
  83883. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  83884. }
  83885. else {
  83886. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  83887. }
  83888. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  83889. parent = parent.parent;
  83890. }
  83891. return this._tmpQuat;
  83892. };
  83893. /**
  83894. * Apply a force
  83895. */
  83896. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  83897. if (this._physicsEngine) {
  83898. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  83899. }
  83900. return this;
  83901. };
  83902. /**
  83903. * Apply an impulse
  83904. */
  83905. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  83906. if (this._physicsEngine) {
  83907. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  83908. }
  83909. return this;
  83910. };
  83911. /**
  83912. * A help function to create a joint.
  83913. */
  83914. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  83915. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  83916. this.addJoint(otherImpostor, joint);
  83917. return this;
  83918. };
  83919. /**
  83920. * Add a joint to this impostor with a different impostor.
  83921. */
  83922. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  83923. this._joints.push({
  83924. otherImpostor: otherImpostor,
  83925. joint: joint
  83926. });
  83927. if (this._physicsEngine) {
  83928. this._physicsEngine.addJoint(this, otherImpostor, joint);
  83929. }
  83930. return this;
  83931. };
  83932. /**
  83933. * Will keep this body still, in a sleep mode.
  83934. */
  83935. PhysicsImpostor.prototype.sleep = function () {
  83936. if (this._physicsEngine) {
  83937. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  83938. }
  83939. return this;
  83940. };
  83941. /**
  83942. * Wake the body up.
  83943. */
  83944. PhysicsImpostor.prototype.wakeUp = function () {
  83945. if (this._physicsEngine) {
  83946. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  83947. }
  83948. return this;
  83949. };
  83950. PhysicsImpostor.prototype.clone = function (newObject) {
  83951. if (!newObject)
  83952. return null;
  83953. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  83954. };
  83955. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  83956. var _this = this;
  83957. //no dispose if no physics engine is available.
  83958. if (!this._physicsEngine) {
  83959. return;
  83960. }
  83961. this._joints.forEach(function (j) {
  83962. if (_this._physicsEngine) {
  83963. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  83964. }
  83965. });
  83966. //dispose the physics body
  83967. this._physicsEngine.removeImpostor(this);
  83968. if (this.parent) {
  83969. this.parent.forceUpdate();
  83970. }
  83971. else {
  83972. /*this._object.getChildMeshes().forEach(function(mesh) {
  83973. if (mesh.physicsImpostor) {
  83974. if (disposeChildren) {
  83975. mesh.physicsImpostor.dispose();
  83976. mesh.physicsImpostor = null;
  83977. }
  83978. }
  83979. })*/
  83980. }
  83981. this._isDisposed = true;
  83982. };
  83983. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  83984. this._deltaPosition.copyFrom(position);
  83985. };
  83986. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  83987. if (!this._deltaRotation) {
  83988. this._deltaRotation = new BABYLON.Quaternion();
  83989. }
  83990. this._deltaRotation.copyFrom(rotation);
  83991. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  83992. };
  83993. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  83994. if (this._physicsEngine) {
  83995. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  83996. }
  83997. return this;
  83998. };
  83999. PhysicsImpostor.prototype.getRadius = function () {
  84000. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  84001. };
  84002. /**
  84003. * Sync a bone with this impostor
  84004. * @param bone The bone to sync to the impostor.
  84005. * @param boneMesh The mesh that the bone is influencing.
  84006. * @param jointPivot The pivot of the joint / bone in local space.
  84007. * @param distToJoint Optional distance from the impostor to the joint.
  84008. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  84009. */
  84010. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  84011. var tempVec = PhysicsImpostor._tmpVecs[0];
  84012. var mesh = this.object;
  84013. if (mesh.rotationQuaternion) {
  84014. if (adjustRotation) {
  84015. var tempQuat = PhysicsImpostor._tmpQuat;
  84016. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  84017. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  84018. }
  84019. else {
  84020. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  84021. }
  84022. }
  84023. tempVec.x = 0;
  84024. tempVec.y = 0;
  84025. tempVec.z = 0;
  84026. if (jointPivot) {
  84027. tempVec.x = jointPivot.x;
  84028. tempVec.y = jointPivot.y;
  84029. tempVec.z = jointPivot.z;
  84030. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  84031. if (distToJoint === undefined || distToJoint === null) {
  84032. distToJoint = jointPivot.length();
  84033. }
  84034. tempVec.x *= distToJoint;
  84035. tempVec.y *= distToJoint;
  84036. tempVec.z *= distToJoint;
  84037. }
  84038. if (bone.getParent()) {
  84039. tempVec.addInPlace(mesh.getAbsolutePosition());
  84040. bone.setAbsolutePosition(tempVec, boneMesh);
  84041. }
  84042. else {
  84043. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  84044. boneMesh.position.x -= tempVec.x;
  84045. boneMesh.position.y -= tempVec.y;
  84046. boneMesh.position.z -= tempVec.z;
  84047. }
  84048. };
  84049. /**
  84050. * Sync impostor to a bone
  84051. * @param bone The bone that the impostor will be synced to.
  84052. * @param boneMesh The mesh that the bone is influencing.
  84053. * @param jointPivot The pivot of the joint / bone in local space.
  84054. * @param distToJoint Optional distance from the impostor to the joint.
  84055. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  84056. * @param boneAxis Optional vector3 axis the bone is aligned with
  84057. */
  84058. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  84059. var mesh = this.object;
  84060. if (mesh.rotationQuaternion) {
  84061. if (adjustRotation) {
  84062. var tempQuat = PhysicsImpostor._tmpQuat;
  84063. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  84064. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  84065. }
  84066. else {
  84067. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  84068. }
  84069. }
  84070. var pos = PhysicsImpostor._tmpVecs[0];
  84071. var boneDir = PhysicsImpostor._tmpVecs[1];
  84072. if (!boneAxis) {
  84073. boneAxis = PhysicsImpostor._tmpVecs[2];
  84074. boneAxis.x = 0;
  84075. boneAxis.y = 1;
  84076. boneAxis.z = 0;
  84077. }
  84078. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  84079. bone.getAbsolutePositionToRef(boneMesh, pos);
  84080. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  84081. distToJoint = jointPivot.length();
  84082. }
  84083. if (distToJoint !== undefined && distToJoint !== null) {
  84084. pos.x += boneDir.x * distToJoint;
  84085. pos.y += boneDir.y * distToJoint;
  84086. pos.z += boneDir.z * distToJoint;
  84087. }
  84088. mesh.setAbsolutePosition(pos);
  84089. };
  84090. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  84091. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  84092. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84093. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  84094. //Impostor types
  84095. PhysicsImpostor.NoImpostor = 0;
  84096. PhysicsImpostor.SphereImpostor = 1;
  84097. PhysicsImpostor.BoxImpostor = 2;
  84098. PhysicsImpostor.PlaneImpostor = 3;
  84099. PhysicsImpostor.MeshImpostor = 4;
  84100. PhysicsImpostor.CylinderImpostor = 7;
  84101. PhysicsImpostor.ParticleImpostor = 8;
  84102. PhysicsImpostor.HeightmapImpostor = 9;
  84103. return PhysicsImpostor;
  84104. }());
  84105. BABYLON.PhysicsImpostor = PhysicsImpostor;
  84106. })(BABYLON || (BABYLON = {}));
  84107. //# sourceMappingURL=babylon.physicsImpostor.js.map
  84108. var BABYLON;
  84109. (function (BABYLON) {
  84110. var PhysicsEngine = /** @class */ (function () {
  84111. function PhysicsEngine(gravity, _physicsPlugin) {
  84112. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  84113. this._physicsPlugin = _physicsPlugin;
  84114. //new methods and parameters
  84115. this._impostors = [];
  84116. this._joints = [];
  84117. if (!this._physicsPlugin.isSupported()) {
  84118. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  84119. + "Please make sure it is included.");
  84120. }
  84121. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  84122. this.setGravity(gravity);
  84123. this.setTimeStep();
  84124. }
  84125. PhysicsEngine.prototype.setGravity = function (gravity) {
  84126. this.gravity = gravity;
  84127. this._physicsPlugin.setGravity(this.gravity);
  84128. };
  84129. /**
  84130. * Set the time step of the physics engine.
  84131. * default is 1/60.
  84132. * To slow it down, enter 1/600 for example.
  84133. * To speed it up, 1/30
  84134. * @param {number} newTimeStep the new timestep to apply to this world.
  84135. */
  84136. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  84137. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  84138. this._physicsPlugin.setTimeStep(newTimeStep);
  84139. };
  84140. /**
  84141. * Get the time step of the physics engine.
  84142. */
  84143. PhysicsEngine.prototype.getTimeStep = function () {
  84144. return this._physicsPlugin.getTimeStep();
  84145. };
  84146. PhysicsEngine.prototype.dispose = function () {
  84147. this._impostors.forEach(function (impostor) {
  84148. impostor.dispose();
  84149. });
  84150. this._physicsPlugin.dispose();
  84151. };
  84152. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  84153. return this._physicsPlugin.name;
  84154. };
  84155. /**
  84156. * Adding a new impostor for the impostor tracking.
  84157. * This will be done by the impostor itself.
  84158. * @param {PhysicsImpostor} impostor the impostor to add
  84159. */
  84160. PhysicsEngine.prototype.addImpostor = function (impostor) {
  84161. impostor.uniqueId = this._impostors.push(impostor);
  84162. //if no parent, generate the body
  84163. if (!impostor.parent) {
  84164. this._physicsPlugin.generatePhysicsBody(impostor);
  84165. }
  84166. };
  84167. /**
  84168. * Remove an impostor from the engine.
  84169. * This impostor and its mesh will not longer be updated by the physics engine.
  84170. * @param {PhysicsImpostor} impostor the impostor to remove
  84171. */
  84172. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  84173. var index = this._impostors.indexOf(impostor);
  84174. if (index > -1) {
  84175. var removed = this._impostors.splice(index, 1);
  84176. //Is it needed?
  84177. if (removed.length) {
  84178. //this will also remove it from the world.
  84179. removed[0].physicsBody = null;
  84180. }
  84181. }
  84182. };
  84183. /**
  84184. * Add a joint to the physics engine
  84185. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  84186. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  84187. * @param {PhysicsJoint} the joint that will connect both impostors.
  84188. */
  84189. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  84190. var impostorJoint = {
  84191. mainImpostor: mainImpostor,
  84192. connectedImpostor: connectedImpostor,
  84193. joint: joint
  84194. };
  84195. joint.physicsPlugin = this._physicsPlugin;
  84196. this._joints.push(impostorJoint);
  84197. this._physicsPlugin.generateJoint(impostorJoint);
  84198. };
  84199. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  84200. var matchingJoints = this._joints.filter(function (impostorJoint) {
  84201. return (impostorJoint.connectedImpostor === connectedImpostor
  84202. && impostorJoint.joint === joint
  84203. && impostorJoint.mainImpostor === mainImpostor);
  84204. });
  84205. if (matchingJoints.length) {
  84206. this._physicsPlugin.removeJoint(matchingJoints[0]);
  84207. //TODO remove it from the list as well
  84208. }
  84209. };
  84210. /**
  84211. * Called by the scene. no need to call it.
  84212. */
  84213. PhysicsEngine.prototype._step = function (delta) {
  84214. var _this = this;
  84215. //check if any mesh has no body / requires an update
  84216. this._impostors.forEach(function (impostor) {
  84217. if (impostor.isBodyInitRequired()) {
  84218. _this._physicsPlugin.generatePhysicsBody(impostor);
  84219. }
  84220. });
  84221. if (delta > 0.1) {
  84222. delta = 0.1;
  84223. }
  84224. else if (delta <= 0) {
  84225. delta = 1.0 / 60.0;
  84226. }
  84227. this._physicsPlugin.executeStep(delta, this._impostors);
  84228. };
  84229. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  84230. return this._physicsPlugin;
  84231. };
  84232. PhysicsEngine.prototype.getImpostors = function () {
  84233. return this._impostors;
  84234. };
  84235. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  84236. for (var i = 0; i < this._impostors.length; ++i) {
  84237. if (this._impostors[i].object === object) {
  84238. return this._impostors[i];
  84239. }
  84240. }
  84241. return null;
  84242. };
  84243. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  84244. for (var i = 0; i < this._impostors.length; ++i) {
  84245. if (this._impostors[i].physicsBody === body) {
  84246. return this._impostors[i];
  84247. }
  84248. }
  84249. return null;
  84250. };
  84251. // Statics
  84252. PhysicsEngine.Epsilon = 0.001;
  84253. return PhysicsEngine;
  84254. }());
  84255. BABYLON.PhysicsEngine = PhysicsEngine;
  84256. })(BABYLON || (BABYLON = {}));
  84257. //# sourceMappingURL=babylon.physicsEngine.js.map
  84258. var BABYLON;
  84259. (function (BABYLON) {
  84260. var PhysicsHelper = /** @class */ (function () {
  84261. function PhysicsHelper(scene) {
  84262. this._scene = scene;
  84263. this._physicsEngine = this._scene.getPhysicsEngine();
  84264. if (!this._physicsEngine) {
  84265. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  84266. }
  84267. }
  84268. /**
  84269. * @param {Vector3} origin the origin of the explosion
  84270. * @param {number} radius the explosion radius
  84271. * @param {number} strength the explosion strength
  84272. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  84273. */
  84274. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  84275. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84276. if (!this._physicsEngine) {
  84277. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  84278. return null;
  84279. }
  84280. var impostors = this._physicsEngine.getImpostors();
  84281. if (impostors.length === 0) {
  84282. return null;
  84283. }
  84284. var event = new PhysicsRadialExplosionEvent(this._scene);
  84285. impostors.forEach(function (impostor) {
  84286. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  84287. if (!impostorForceAndContactPoint) {
  84288. return;
  84289. }
  84290. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84291. });
  84292. event.dispose(false);
  84293. return event;
  84294. };
  84295. /**
  84296. * @param {Vector3} origin the origin of the explosion
  84297. * @param {number} radius the explosion radius
  84298. * @param {number} strength the explosion strength
  84299. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  84300. */
  84301. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  84302. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84303. if (!this._physicsEngine) {
  84304. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84305. return null;
  84306. }
  84307. var impostors = this._physicsEngine.getImpostors();
  84308. if (impostors.length === 0) {
  84309. return null;
  84310. }
  84311. var event = new PhysicsRadialExplosionEvent(this._scene);
  84312. impostors.forEach(function (impostor) {
  84313. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  84314. if (!impostorForceAndContactPoint) {
  84315. return;
  84316. }
  84317. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84318. });
  84319. event.dispose(false);
  84320. return event;
  84321. };
  84322. /**
  84323. * @param {Vector3} origin the origin of the explosion
  84324. * @param {number} radius the explosion radius
  84325. * @param {number} strength the explosion strength
  84326. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  84327. */
  84328. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  84329. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84330. if (!this._physicsEngine) {
  84331. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84332. return null;
  84333. }
  84334. var impostors = this._physicsEngine.getImpostors();
  84335. if (impostors.length === 0) {
  84336. return null;
  84337. }
  84338. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  84339. event.dispose(false);
  84340. return event;
  84341. };
  84342. /**
  84343. * @param {Vector3} origin the origin of the updraft
  84344. * @param {number} radius the radius of the updraft
  84345. * @param {number} strength the strength of the updraft
  84346. * @param {number} height the height of the updraft
  84347. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  84348. */
  84349. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  84350. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  84351. if (!this._physicsEngine) {
  84352. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84353. return null;
  84354. }
  84355. if (this._physicsEngine.getImpostors().length === 0) {
  84356. return null;
  84357. }
  84358. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  84359. event.dispose(false);
  84360. return event;
  84361. };
  84362. /**
  84363. * @param {Vector3} origin the of the vortex
  84364. * @param {number} radius the radius of the vortex
  84365. * @param {number} strength the strength of the vortex
  84366. * @param {number} height the height of the vortex
  84367. */
  84368. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  84369. if (!this._physicsEngine) {
  84370. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84371. return null;
  84372. }
  84373. if (this._physicsEngine.getImpostors().length === 0) {
  84374. return null;
  84375. }
  84376. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  84377. event.dispose(false);
  84378. return event;
  84379. };
  84380. return PhysicsHelper;
  84381. }());
  84382. BABYLON.PhysicsHelper = PhysicsHelper;
  84383. /***** Radial explosion *****/
  84384. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  84385. function PhysicsRadialExplosionEvent(scene) {
  84386. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  84387. this._rays = [];
  84388. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  84389. this._scene = scene;
  84390. }
  84391. /**
  84392. * Returns the data related to the radial explosion event (sphere & rays).
  84393. * @returns {PhysicsRadialExplosionEventData}
  84394. */
  84395. PhysicsRadialExplosionEvent.prototype.getData = function () {
  84396. this._dataFetched = true;
  84397. return {
  84398. sphere: this._sphere,
  84399. rays: this._rays,
  84400. };
  84401. };
  84402. /**
  84403. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  84404. * @param impostor
  84405. * @param {Vector3} origin the origin of the explosion
  84406. * @param {number} radius the explosion radius
  84407. * @param {number} strength the explosion strength
  84408. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  84409. * @returns {Nullable<PhysicsForceAndContactPoint>}
  84410. */
  84411. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  84412. if (impostor.mass === 0) {
  84413. return null;
  84414. }
  84415. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  84416. return null;
  84417. }
  84418. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  84419. return null;
  84420. }
  84421. var impostorObjectCenter = impostor.getObjectCenter();
  84422. var direction = impostorObjectCenter.subtract(origin);
  84423. var ray = new BABYLON.Ray(origin, direction, radius);
  84424. this._rays.push(ray);
  84425. var hit = ray.intersectsMesh(impostor.object);
  84426. var contactPoint = hit.pickedPoint;
  84427. if (!contactPoint) {
  84428. return null;
  84429. }
  84430. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  84431. if (distanceFromOrigin > radius) {
  84432. return null;
  84433. }
  84434. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  84435. ? strength
  84436. : strength * (1 - (distanceFromOrigin / radius));
  84437. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  84438. return { force: force, contactPoint: contactPoint };
  84439. };
  84440. /**
  84441. * Disposes the sphere.
  84442. * @param {bolean} force
  84443. */
  84444. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  84445. var _this = this;
  84446. if (force === void 0) { force = true; }
  84447. if (force) {
  84448. this._sphere.dispose();
  84449. }
  84450. else {
  84451. setTimeout(function () {
  84452. if (!_this._dataFetched) {
  84453. _this._sphere.dispose();
  84454. }
  84455. }, 0);
  84456. }
  84457. };
  84458. /*** Helpers ***/
  84459. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  84460. if (!this._sphere) {
  84461. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  84462. this._sphere.isVisible = false;
  84463. }
  84464. };
  84465. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  84466. var impostorObject = impostor.object;
  84467. this._prepareSphere();
  84468. this._sphere.position = origin;
  84469. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  84470. this._sphere._updateBoundingInfo();
  84471. this._sphere.computeWorldMatrix(true);
  84472. return this._sphere.intersectsMesh(impostorObject, true);
  84473. };
  84474. return PhysicsRadialExplosionEvent;
  84475. }());
  84476. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  84477. /***** Gravitational Field *****/
  84478. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  84479. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  84480. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84481. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84482. this._physicsHelper = physicsHelper;
  84483. this._scene = scene;
  84484. this._origin = origin;
  84485. this._radius = radius;
  84486. this._strength = strength;
  84487. this._falloff = falloff;
  84488. this._tickCallback = this._tick.bind(this);
  84489. }
  84490. /**
  84491. * Returns the data related to the gravitational field event (sphere).
  84492. * @returns {PhysicsGravitationalFieldEventData}
  84493. */
  84494. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  84495. this._dataFetched = true;
  84496. return {
  84497. sphere: this._sphere,
  84498. };
  84499. };
  84500. /**
  84501. * Enables the gravitational field.
  84502. */
  84503. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  84504. this._tickCallback.call(this);
  84505. this._scene.registerBeforeRender(this._tickCallback);
  84506. };
  84507. /**
  84508. * Disables the gravitational field.
  84509. */
  84510. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  84511. this._scene.unregisterBeforeRender(this._tickCallback);
  84512. };
  84513. /**
  84514. * Disposes the sphere.
  84515. * @param {bolean} force
  84516. */
  84517. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  84518. var _this = this;
  84519. if (force === void 0) { force = true; }
  84520. if (force) {
  84521. this._sphere.dispose();
  84522. }
  84523. else {
  84524. setTimeout(function () {
  84525. if (!_this._dataFetched) {
  84526. _this._sphere.dispose();
  84527. }
  84528. }, 0);
  84529. }
  84530. };
  84531. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  84532. // Since the params won't change, we fetch the event only once
  84533. if (this._sphere) {
  84534. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  84535. }
  84536. else {
  84537. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  84538. if (radialExplosionEvent) {
  84539. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  84540. }
  84541. }
  84542. };
  84543. return PhysicsGravitationalFieldEvent;
  84544. }());
  84545. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  84546. /***** Updraft *****/
  84547. var PhysicsUpdraftEvent = /** @class */ (function () {
  84548. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  84549. this._scene = _scene;
  84550. this._origin = _origin;
  84551. this._radius = _radius;
  84552. this._strength = _strength;
  84553. this._height = _height;
  84554. this._updraftMode = _updraftMode;
  84555. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  84556. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  84557. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  84558. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84559. this._physicsEngine = this._scene.getPhysicsEngine();
  84560. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  84561. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  84562. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  84563. this._originDirection = this._origin.subtract(this._originTop).normalize();
  84564. }
  84565. this._tickCallback = this._tick.bind(this);
  84566. }
  84567. /**
  84568. * Returns the data related to the updraft event (cylinder).
  84569. * @returns {PhysicsUpdraftEventData}
  84570. */
  84571. PhysicsUpdraftEvent.prototype.getData = function () {
  84572. this._dataFetched = true;
  84573. return {
  84574. cylinder: this._cylinder,
  84575. };
  84576. };
  84577. /**
  84578. * Enables the updraft.
  84579. */
  84580. PhysicsUpdraftEvent.prototype.enable = function () {
  84581. this._tickCallback.call(this);
  84582. this._scene.registerBeforeRender(this._tickCallback);
  84583. };
  84584. /**
  84585. * Disables the cortex.
  84586. */
  84587. PhysicsUpdraftEvent.prototype.disable = function () {
  84588. this._scene.unregisterBeforeRender(this._tickCallback);
  84589. };
  84590. /**
  84591. * Disposes the sphere.
  84592. * @param {bolean} force
  84593. */
  84594. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  84595. var _this = this;
  84596. if (force === void 0) { force = true; }
  84597. if (force) {
  84598. this._cylinder.dispose();
  84599. }
  84600. else {
  84601. setTimeout(function () {
  84602. if (!_this._dataFetched) {
  84603. _this._cylinder.dispose();
  84604. }
  84605. }, 0);
  84606. }
  84607. };
  84608. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  84609. if (impostor.mass === 0) {
  84610. return null;
  84611. }
  84612. if (!this._intersectsWithCylinder(impostor)) {
  84613. return null;
  84614. }
  84615. var impostorObjectCenter = impostor.getObjectCenter();
  84616. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  84617. var direction = this._originDirection;
  84618. }
  84619. else {
  84620. var direction = impostorObjectCenter.subtract(this._originTop);
  84621. }
  84622. var multiplier = this._strength * -1;
  84623. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  84624. return { force: force, contactPoint: impostorObjectCenter };
  84625. };
  84626. PhysicsUpdraftEvent.prototype._tick = function () {
  84627. var _this = this;
  84628. this._physicsEngine.getImpostors().forEach(function (impostor) {
  84629. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  84630. if (!impostorForceAndContactPoint) {
  84631. return;
  84632. }
  84633. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84634. });
  84635. };
  84636. /*** Helpers ***/
  84637. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  84638. if (!this._cylinder) {
  84639. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  84640. height: this._height,
  84641. diameter: this._radius * 2,
  84642. }, this._scene);
  84643. this._cylinder.isVisible = false;
  84644. }
  84645. };
  84646. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  84647. var impostorObject = impostor.object;
  84648. this._prepareCylinder();
  84649. this._cylinder.position = this._cylinderPosition;
  84650. return this._cylinder.intersectsMesh(impostorObject, true);
  84651. };
  84652. return PhysicsUpdraftEvent;
  84653. }());
  84654. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  84655. /***** Vortex *****/
  84656. var PhysicsVortexEvent = /** @class */ (function () {
  84657. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  84658. this._scene = _scene;
  84659. this._origin = _origin;
  84660. this._radius = _radius;
  84661. this._strength = _strength;
  84662. this._height = _height;
  84663. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  84664. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  84665. this._updraftMultiplier = 0.02;
  84666. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  84667. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84668. this._physicsEngine = this._scene.getPhysicsEngine();
  84669. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  84670. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  84671. this._tickCallback = this._tick.bind(this);
  84672. }
  84673. /**
  84674. * Returns the data related to the vortex event (cylinder).
  84675. * @returns {PhysicsVortexEventData}
  84676. */
  84677. PhysicsVortexEvent.prototype.getData = function () {
  84678. this._dataFetched = true;
  84679. return {
  84680. cylinder: this._cylinder,
  84681. };
  84682. };
  84683. /**
  84684. * Enables the vortex.
  84685. */
  84686. PhysicsVortexEvent.prototype.enable = function () {
  84687. this._tickCallback.call(this);
  84688. this._scene.registerBeforeRender(this._tickCallback);
  84689. };
  84690. /**
  84691. * Disables the cortex.
  84692. */
  84693. PhysicsVortexEvent.prototype.disable = function () {
  84694. this._scene.unregisterBeforeRender(this._tickCallback);
  84695. };
  84696. /**
  84697. * Disposes the sphere.
  84698. * @param {bolean} force
  84699. */
  84700. PhysicsVortexEvent.prototype.dispose = function (force) {
  84701. var _this = this;
  84702. if (force === void 0) { force = true; }
  84703. if (force) {
  84704. this._cylinder.dispose();
  84705. }
  84706. else {
  84707. setTimeout(function () {
  84708. if (!_this._dataFetched) {
  84709. _this._cylinder.dispose();
  84710. }
  84711. }, 0);
  84712. }
  84713. };
  84714. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  84715. if (impostor.mass === 0) {
  84716. return null;
  84717. }
  84718. if (!this._intersectsWithCylinder(impostor)) {
  84719. return null;
  84720. }
  84721. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  84722. return null;
  84723. }
  84724. var impostorObjectCenter = impostor.getObjectCenter();
  84725. 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)
  84726. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  84727. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  84728. var hit = ray.intersectsMesh(impostor.object);
  84729. var contactPoint = hit.pickedPoint;
  84730. if (!contactPoint) {
  84731. return null;
  84732. }
  84733. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  84734. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  84735. var directionToOrigin = contactPoint.normalize();
  84736. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  84737. directionToOrigin = directionToOrigin.negate();
  84738. }
  84739. // TODO: find a more physically based solution
  84740. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  84741. var forceX = directionToOrigin.x * this._strength / 8;
  84742. var forceY = directionToOrigin.y * this._updraftMultiplier;
  84743. var forceZ = directionToOrigin.z * this._strength / 8;
  84744. }
  84745. else {
  84746. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  84747. var forceY = this._originTop.y * this._updraftMultiplier;
  84748. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  84749. }
  84750. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  84751. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  84752. return { force: force, contactPoint: impostorObjectCenter };
  84753. };
  84754. PhysicsVortexEvent.prototype._tick = function () {
  84755. var _this = this;
  84756. this._physicsEngine.getImpostors().forEach(function (impostor) {
  84757. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  84758. if (!impostorForceAndContactPoint) {
  84759. return;
  84760. }
  84761. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84762. });
  84763. };
  84764. /*** Helpers ***/
  84765. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  84766. if (!this._cylinder) {
  84767. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  84768. height: this._height,
  84769. diameter: this._radius * 2,
  84770. }, this._scene);
  84771. this._cylinder.isVisible = false;
  84772. }
  84773. };
  84774. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  84775. var impostorObject = impostor.object;
  84776. this._prepareCylinder();
  84777. this._cylinder.position = this._cylinderPosition;
  84778. return this._cylinder.intersectsMesh(impostorObject, true);
  84779. };
  84780. return PhysicsVortexEvent;
  84781. }());
  84782. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  84783. /***** Enums *****/
  84784. /**
  84785. * The strenght of the force in correspondence to the distance of the affected object
  84786. */
  84787. var PhysicsRadialImpulseFalloff;
  84788. (function (PhysicsRadialImpulseFalloff) {
  84789. /** Defines that impulse is constant in strength across it's whole radius */
  84790. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  84791. /** DEfines that impulse gets weaker if it's further from the origin */
  84792. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  84793. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  84794. /**
  84795. * The strenght of the force in correspondence to the distance of the affected object
  84796. */
  84797. var PhysicsUpdraftMode;
  84798. (function (PhysicsUpdraftMode) {
  84799. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  84800. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  84801. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  84802. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  84803. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  84804. })(BABYLON || (BABYLON = {}));
  84805. //# sourceMappingURL=babylon.physicsHelper.js.map
  84806. var BABYLON;
  84807. (function (BABYLON) {
  84808. var CannonJSPlugin = /** @class */ (function () {
  84809. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  84810. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  84811. if (iterations === void 0) { iterations = 10; }
  84812. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  84813. this.name = "CannonJSPlugin";
  84814. this._physicsMaterials = new Array();
  84815. this._fixedTimeStep = 1 / 60;
  84816. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  84817. this.BJSCANNON = CANNON;
  84818. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  84819. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  84820. this._tmpPosition = BABYLON.Vector3.Zero();
  84821. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  84822. this._tmpUnityRotation = new BABYLON.Quaternion();
  84823. if (!this.isSupported()) {
  84824. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  84825. return;
  84826. }
  84827. this._extendNamespace();
  84828. this.world = new this.BJSCANNON.World();
  84829. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  84830. this.world.solver.iterations = iterations;
  84831. }
  84832. CannonJSPlugin.prototype.setGravity = function (gravity) {
  84833. this.world.gravity.copy(gravity);
  84834. };
  84835. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  84836. this._fixedTimeStep = timeStep;
  84837. };
  84838. CannonJSPlugin.prototype.getTimeStep = function () {
  84839. return this._fixedTimeStep;
  84840. };
  84841. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  84842. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  84843. };
  84844. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  84845. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  84846. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  84847. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  84848. };
  84849. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  84850. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  84851. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  84852. impostor.physicsBody.applyForce(impulse, worldPoint);
  84853. };
  84854. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  84855. //parent-child relationship. Does this impostor has a parent impostor?
  84856. if (impostor.parent) {
  84857. if (impostor.physicsBody) {
  84858. this.removePhysicsBody(impostor);
  84859. //TODO is that needed?
  84860. impostor.forceUpdate();
  84861. }
  84862. return;
  84863. }
  84864. //should a new body be created for this impostor?
  84865. if (impostor.isBodyInitRequired()) {
  84866. var shape = this._createShape(impostor);
  84867. //unregister events, if body is being changed
  84868. var oldBody = impostor.physicsBody;
  84869. if (oldBody) {
  84870. this.removePhysicsBody(impostor);
  84871. }
  84872. //create the body and material
  84873. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  84874. var bodyCreationObject = {
  84875. mass: impostor.getParam("mass"),
  84876. material: material
  84877. };
  84878. // A simple extend, in case native options were used.
  84879. var nativeOptions = impostor.getParam("nativeOptions");
  84880. for (var key in nativeOptions) {
  84881. if (nativeOptions.hasOwnProperty(key)) {
  84882. bodyCreationObject[key] = nativeOptions[key];
  84883. }
  84884. }
  84885. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  84886. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  84887. this.world.addEventListener("preStep", impostor.beforeStep);
  84888. this.world.addEventListener("postStep", impostor.afterStep);
  84889. impostor.physicsBody.addShape(shape);
  84890. this.world.add(impostor.physicsBody);
  84891. //try to keep the body moving in the right direction by taking old properties.
  84892. //Should be tested!
  84893. if (oldBody) {
  84894. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  84895. impostor.physicsBody[param].copy(oldBody[param]);
  84896. });
  84897. }
  84898. this._processChildMeshes(impostor);
  84899. }
  84900. //now update the body's transformation
  84901. this._updatePhysicsBodyTransformation(impostor);
  84902. };
  84903. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  84904. var _this = this;
  84905. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  84906. var currentRotation = mainImpostor.object.rotationQuaternion;
  84907. if (meshChildren.length) {
  84908. var processMesh = function (localPosition, mesh) {
  84909. if (!currentRotation || !mesh.rotationQuaternion) {
  84910. return;
  84911. }
  84912. var childImpostor = mesh.getPhysicsImpostor();
  84913. if (childImpostor) {
  84914. var parent = childImpostor.parent;
  84915. if (parent !== mainImpostor) {
  84916. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  84917. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  84918. if (childImpostor.physicsBody) {
  84919. _this.removePhysicsBody(childImpostor);
  84920. childImpostor.physicsBody = null;
  84921. }
  84922. childImpostor.parent = mainImpostor;
  84923. childImpostor.resetUpdateFlags();
  84924. 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));
  84925. //Add the mass of the children.
  84926. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  84927. }
  84928. }
  84929. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  84930. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  84931. };
  84932. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  84933. }
  84934. };
  84935. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  84936. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  84937. this.world.removeEventListener("preStep", impostor.beforeStep);
  84938. this.world.removeEventListener("postStep", impostor.afterStep);
  84939. this.world.remove(impostor.physicsBody);
  84940. };
  84941. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  84942. var mainBody = impostorJoint.mainImpostor.physicsBody;
  84943. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  84944. if (!mainBody || !connectedBody) {
  84945. return;
  84946. }
  84947. var constraint;
  84948. var jointData = impostorJoint.joint.jointData;
  84949. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  84950. var constraintData = {
  84951. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  84952. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  84953. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  84954. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  84955. maxForce: jointData.nativeParams.maxForce,
  84956. collideConnected: !!jointData.collision
  84957. };
  84958. switch (impostorJoint.joint.type) {
  84959. case BABYLON.PhysicsJoint.HingeJoint:
  84960. case BABYLON.PhysicsJoint.Hinge2Joint:
  84961. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  84962. break;
  84963. case BABYLON.PhysicsJoint.DistanceJoint:
  84964. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  84965. break;
  84966. case BABYLON.PhysicsJoint.SpringJoint:
  84967. var springData = jointData;
  84968. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  84969. restLength: springData.length,
  84970. stiffness: springData.stiffness,
  84971. damping: springData.damping,
  84972. localAnchorA: constraintData.pivotA,
  84973. localAnchorB: constraintData.pivotB
  84974. });
  84975. break;
  84976. case BABYLON.PhysicsJoint.LockJoint:
  84977. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  84978. break;
  84979. case BABYLON.PhysicsJoint.PointToPointJoint:
  84980. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  84981. default:
  84982. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  84983. break;
  84984. }
  84985. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  84986. constraint.collideConnected = !!jointData.collision;
  84987. impostorJoint.joint.physicsJoint = constraint;
  84988. //don't add spring as constraint, as it is not one.
  84989. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  84990. this.world.addConstraint(constraint);
  84991. }
  84992. else {
  84993. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  84994. constraint.applyForce();
  84995. });
  84996. }
  84997. };
  84998. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  84999. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  85000. };
  85001. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  85002. var index;
  85003. var mat;
  85004. for (index = 0; index < this._physicsMaterials.length; index++) {
  85005. mat = this._physicsMaterials[index];
  85006. if (mat.friction === friction && mat.restitution === restitution) {
  85007. return mat;
  85008. }
  85009. }
  85010. var currentMat = new this.BJSCANNON.Material(name);
  85011. currentMat.friction = friction;
  85012. currentMat.restitution = restitution;
  85013. this._physicsMaterials.push(currentMat);
  85014. return currentMat;
  85015. };
  85016. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  85017. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  85018. };
  85019. CannonJSPlugin.prototype._createShape = function (impostor) {
  85020. var object = impostor.object;
  85021. var returnValue;
  85022. var extendSize = impostor.getObjectExtendSize();
  85023. switch (impostor.type) {
  85024. case BABYLON.PhysicsImpostor.SphereImpostor:
  85025. var radiusX = extendSize.x;
  85026. var radiusY = extendSize.y;
  85027. var radiusZ = extendSize.z;
  85028. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  85029. break;
  85030. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  85031. case BABYLON.PhysicsImpostor.CylinderImpostor:
  85032. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  85033. break;
  85034. case BABYLON.PhysicsImpostor.BoxImpostor:
  85035. var box = extendSize.scale(0.5);
  85036. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  85037. break;
  85038. case BABYLON.PhysicsImpostor.PlaneImpostor:
  85039. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  85040. returnValue = new this.BJSCANNON.Plane();
  85041. break;
  85042. case BABYLON.PhysicsImpostor.MeshImpostor:
  85043. // should transform the vertex data to world coordinates!!
  85044. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  85045. var rawFaces = object.getIndices ? object.getIndices() : [];
  85046. if (!rawVerts)
  85047. return;
  85048. // get only scale! so the object could transform correctly.
  85049. var oldPosition = object.position.clone();
  85050. var oldRotation = object.rotation && object.rotation.clone();
  85051. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  85052. object.position.copyFromFloats(0, 0, 0);
  85053. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  85054. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  85055. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  85056. var transform = object.computeWorldMatrix(true);
  85057. // convert rawVerts to object space
  85058. var temp = new Array();
  85059. var index;
  85060. for (index = 0; index < rawVerts.length; index += 3) {
  85061. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  85062. }
  85063. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  85064. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  85065. //now set back the transformation!
  85066. object.position.copyFrom(oldPosition);
  85067. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  85068. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  85069. break;
  85070. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  85071. var oldPosition2 = object.position.clone();
  85072. var oldRotation2 = object.rotation && object.rotation.clone();
  85073. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  85074. object.position.copyFromFloats(0, 0, 0);
  85075. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  85076. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  85077. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  85078. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  85079. returnValue = this._createHeightmap(object);
  85080. object.position.copyFrom(oldPosition2);
  85081. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  85082. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  85083. object.computeWorldMatrix(true);
  85084. break;
  85085. case BABYLON.PhysicsImpostor.ParticleImpostor:
  85086. returnValue = new this.BJSCANNON.Particle();
  85087. break;
  85088. }
  85089. return returnValue;
  85090. };
  85091. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  85092. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85093. var transform = object.computeWorldMatrix(true);
  85094. // convert rawVerts to object space
  85095. var temp = new Array();
  85096. var index;
  85097. for (index = 0; index < pos.length; index += 3) {
  85098. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  85099. }
  85100. pos = temp;
  85101. var matrix = new Array();
  85102. //For now pointDepth will not be used and will be automatically calculated.
  85103. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  85104. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  85105. var boundingInfo = object.getBoundingInfo();
  85106. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  85107. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  85108. var elementSize = dim * 2 / arraySize;
  85109. for (var i = 0; i < pos.length; i = i + 3) {
  85110. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  85111. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  85112. var y = -pos[i + 2] + minY;
  85113. if (!matrix[x]) {
  85114. matrix[x] = [];
  85115. }
  85116. if (!matrix[x][z]) {
  85117. matrix[x][z] = y;
  85118. }
  85119. matrix[x][z] = Math.max(y, matrix[x][z]);
  85120. }
  85121. for (var x = 0; x <= arraySize; ++x) {
  85122. if (!matrix[x]) {
  85123. var loc = 1;
  85124. while (!matrix[(x + loc) % arraySize]) {
  85125. loc++;
  85126. }
  85127. matrix[x] = matrix[(x + loc) % arraySize].slice();
  85128. //console.log("missing x", x);
  85129. }
  85130. for (var z = 0; z <= arraySize; ++z) {
  85131. if (!matrix[x][z]) {
  85132. var loc = 1;
  85133. var newValue;
  85134. while (newValue === undefined) {
  85135. newValue = matrix[x][(z + loc++) % arraySize];
  85136. }
  85137. matrix[x][z] = newValue;
  85138. }
  85139. }
  85140. }
  85141. var shape = new this.BJSCANNON.Heightfield(matrix, {
  85142. elementSize: elementSize
  85143. });
  85144. //For future reference, needed for body transformation
  85145. shape.minY = minY;
  85146. return shape;
  85147. };
  85148. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  85149. var object = impostor.object;
  85150. //make sure it is updated...
  85151. object.computeWorldMatrix && object.computeWorldMatrix(true);
  85152. // The delta between the mesh position and the mesh bounding box center
  85153. var bInfo = object.getBoundingInfo();
  85154. if (!bInfo)
  85155. return;
  85156. var center = impostor.getObjectCenter();
  85157. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  85158. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  85159. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  85160. this._tmpPosition.copyFrom(center);
  85161. var quaternion = object.rotationQuaternion;
  85162. if (!quaternion) {
  85163. return;
  85164. }
  85165. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  85166. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  85167. //-90 DEG in X, precalculated
  85168. quaternion = quaternion.multiply(this._minus90X);
  85169. //Invert! (Precalculated, 90 deg in X)
  85170. //No need to clone. this will never change.
  85171. impostor.setDeltaRotation(this._plus90X);
  85172. }
  85173. //If it is a heightfield, if should be centered.
  85174. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  85175. var mesh = object;
  85176. var boundingInfo = mesh.getBoundingInfo();
  85177. //calculate the correct body position:
  85178. var rotationQuaternion = mesh.rotationQuaternion;
  85179. mesh.rotationQuaternion = this._tmpUnityRotation;
  85180. mesh.computeWorldMatrix(true);
  85181. //get original center with no rotation
  85182. var c = center.clone();
  85183. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  85184. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  85185. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  85186. mesh.setPreTransformMatrix(p);
  85187. mesh.computeWorldMatrix(true);
  85188. //calculate the translation
  85189. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  85190. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  85191. //add it inverted to the delta
  85192. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  85193. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  85194. //rotation is back
  85195. mesh.rotationQuaternion = rotationQuaternion;
  85196. mesh.setPreTransformMatrix(oldPivot);
  85197. mesh.computeWorldMatrix(true);
  85198. }
  85199. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  85200. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  85201. //this._tmpPosition.copyFrom(object.position);
  85202. }
  85203. impostor.setDeltaPosition(this._tmpDeltaPosition);
  85204. //Now update the impostor object
  85205. impostor.physicsBody.position.copy(this._tmpPosition);
  85206. impostor.physicsBody.quaternion.copy(quaternion);
  85207. };
  85208. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  85209. impostor.object.position.copyFrom(impostor.physicsBody.position);
  85210. if (impostor.object.rotationQuaternion) {
  85211. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  85212. }
  85213. };
  85214. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  85215. impostor.physicsBody.position.copy(newPosition);
  85216. impostor.physicsBody.quaternion.copy(newRotation);
  85217. };
  85218. CannonJSPlugin.prototype.isSupported = function () {
  85219. return this.BJSCANNON !== undefined;
  85220. };
  85221. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  85222. impostor.physicsBody.velocity.copy(velocity);
  85223. };
  85224. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  85225. impostor.physicsBody.angularVelocity.copy(velocity);
  85226. };
  85227. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  85228. var v = impostor.physicsBody.velocity;
  85229. if (!v) {
  85230. return null;
  85231. }
  85232. return new BABYLON.Vector3(v.x, v.y, v.z);
  85233. };
  85234. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  85235. var v = impostor.physicsBody.angularVelocity;
  85236. if (!v) {
  85237. return null;
  85238. }
  85239. return new BABYLON.Vector3(v.x, v.y, v.z);
  85240. };
  85241. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  85242. impostor.physicsBody.mass = mass;
  85243. impostor.physicsBody.updateMassProperties();
  85244. };
  85245. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  85246. return impostor.physicsBody.mass;
  85247. };
  85248. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  85249. return impostor.physicsBody.material.friction;
  85250. };
  85251. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  85252. impostor.physicsBody.material.friction = friction;
  85253. };
  85254. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  85255. return impostor.physicsBody.material.restitution;
  85256. };
  85257. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  85258. impostor.physicsBody.material.restitution = restitution;
  85259. };
  85260. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  85261. impostor.physicsBody.sleep();
  85262. };
  85263. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  85264. impostor.physicsBody.wakeUp();
  85265. };
  85266. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  85267. joint.physicsJoint.distance = maxDistance;
  85268. };
  85269. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  85270. // if (!motorIndex) {
  85271. // joint.physicsJoint.enableMotor();
  85272. // }
  85273. // }
  85274. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  85275. // if (!motorIndex) {
  85276. // joint.physicsJoint.disableMotor();
  85277. // }
  85278. // }
  85279. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  85280. if (!motorIndex) {
  85281. joint.physicsJoint.enableMotor();
  85282. joint.physicsJoint.setMotorSpeed(speed);
  85283. if (maxForce) {
  85284. this.setLimit(joint, maxForce);
  85285. }
  85286. }
  85287. };
  85288. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  85289. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  85290. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  85291. };
  85292. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  85293. var body = impostor.physicsBody;
  85294. mesh.position.x = body.position.x;
  85295. mesh.position.y = body.position.y;
  85296. mesh.position.z = body.position.z;
  85297. if (mesh.rotationQuaternion) {
  85298. mesh.rotationQuaternion.x = body.quaternion.x;
  85299. mesh.rotationQuaternion.y = body.quaternion.y;
  85300. mesh.rotationQuaternion.z = body.quaternion.z;
  85301. mesh.rotationQuaternion.w = body.quaternion.w;
  85302. }
  85303. };
  85304. CannonJSPlugin.prototype.getRadius = function (impostor) {
  85305. var shape = impostor.physicsBody.shapes[0];
  85306. return shape.boundingSphereRadius;
  85307. };
  85308. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  85309. var shape = impostor.physicsBody.shapes[0];
  85310. result.x = shape.halfExtents.x * 2;
  85311. result.y = shape.halfExtents.y * 2;
  85312. result.z = shape.halfExtents.z * 2;
  85313. };
  85314. CannonJSPlugin.prototype.dispose = function () {
  85315. };
  85316. CannonJSPlugin.prototype._extendNamespace = function () {
  85317. //this will force cannon to execute at least one step when using interpolation
  85318. var step_tmp1 = new this.BJSCANNON.Vec3();
  85319. var Engine = this.BJSCANNON;
  85320. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  85321. maxSubSteps = maxSubSteps || 10;
  85322. timeSinceLastCalled = timeSinceLastCalled || 0;
  85323. if (timeSinceLastCalled === 0) {
  85324. this.internalStep(dt);
  85325. this.time += dt;
  85326. }
  85327. else {
  85328. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  85329. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  85330. var t0 = performance.now();
  85331. for (var i = 0; i !== internalSteps; i++) {
  85332. this.internalStep(dt);
  85333. if (performance.now() - t0 > dt * 1000) {
  85334. break;
  85335. }
  85336. }
  85337. this.time += timeSinceLastCalled;
  85338. var h = this.time % dt;
  85339. var h_div_dt = h / dt;
  85340. var interpvelo = step_tmp1;
  85341. var bodies = this.bodies;
  85342. for (var j = 0; j !== bodies.length; j++) {
  85343. var b = bodies[j];
  85344. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  85345. b.position.vsub(b.previousPosition, interpvelo);
  85346. interpvelo.scale(h_div_dt, interpvelo);
  85347. b.position.vadd(interpvelo, b.interpolatedPosition);
  85348. }
  85349. else {
  85350. b.interpolatedPosition.copy(b.position);
  85351. b.interpolatedQuaternion.copy(b.quaternion);
  85352. }
  85353. }
  85354. }
  85355. };
  85356. };
  85357. return CannonJSPlugin;
  85358. }());
  85359. BABYLON.CannonJSPlugin = CannonJSPlugin;
  85360. })(BABYLON || (BABYLON = {}));
  85361. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  85362. var BABYLON;
  85363. (function (BABYLON) {
  85364. var OimoJSPlugin = /** @class */ (function () {
  85365. function OimoJSPlugin(iterations) {
  85366. this.name = "OimoJSPlugin";
  85367. this._tmpImpostorsArray = [];
  85368. this._tmpPositionVector = BABYLON.Vector3.Zero();
  85369. this.BJSOIMO = OIMO;
  85370. this.world = new this.BJSOIMO.World({
  85371. iterations: iterations
  85372. });
  85373. this.world.clear();
  85374. }
  85375. OimoJSPlugin.prototype.setGravity = function (gravity) {
  85376. this.world.gravity.copy(gravity);
  85377. };
  85378. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  85379. this.world.timeStep = timeStep;
  85380. };
  85381. OimoJSPlugin.prototype.getTimeStep = function () {
  85382. return this.world.timeStep;
  85383. };
  85384. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  85385. var _this = this;
  85386. impostors.forEach(function (impostor) {
  85387. impostor.beforeStep();
  85388. });
  85389. this.world.step();
  85390. impostors.forEach(function (impostor) {
  85391. impostor.afterStep();
  85392. //update the ordered impostors array
  85393. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  85394. });
  85395. //check for collisions
  85396. var contact = this.world.contacts;
  85397. while (contact !== null) {
  85398. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  85399. contact = contact.next;
  85400. continue;
  85401. }
  85402. //is this body colliding with any other? get the impostor
  85403. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  85404. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  85405. if (!mainImpostor || !collidingImpostor) {
  85406. contact = contact.next;
  85407. continue;
  85408. }
  85409. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  85410. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  85411. contact = contact.next;
  85412. }
  85413. };
  85414. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  85415. var mass = impostor.physicsBody.mass;
  85416. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  85417. };
  85418. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  85419. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  85420. this.applyImpulse(impostor, force, contactPoint);
  85421. };
  85422. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  85423. var _this = this;
  85424. //parent-child relationship. Does this impostor has a parent impostor?
  85425. if (impostor.parent) {
  85426. if (impostor.physicsBody) {
  85427. this.removePhysicsBody(impostor);
  85428. //TODO is that needed?
  85429. impostor.forceUpdate();
  85430. }
  85431. return;
  85432. }
  85433. if (impostor.isBodyInitRequired()) {
  85434. var bodyConfig = {
  85435. name: impostor.uniqueId,
  85436. //Oimo must have mass, also for static objects.
  85437. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  85438. size: [],
  85439. type: [],
  85440. pos: [],
  85441. posShape: [],
  85442. rot: [],
  85443. rotShape: [],
  85444. move: impostor.getParam("mass") !== 0,
  85445. density: impostor.getParam("mass"),
  85446. friction: impostor.getParam("friction"),
  85447. restitution: impostor.getParam("restitution"),
  85448. //Supporting older versions of Oimo
  85449. world: this.world
  85450. };
  85451. var impostors = [impostor];
  85452. var addToArray = function (parent) {
  85453. if (!parent.getChildMeshes)
  85454. return;
  85455. parent.getChildMeshes().forEach(function (m) {
  85456. if (m.physicsImpostor) {
  85457. impostors.push(m.physicsImpostor);
  85458. //m.physicsImpostor._init();
  85459. }
  85460. });
  85461. };
  85462. addToArray(impostor.object);
  85463. var checkWithEpsilon_1 = function (value) {
  85464. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  85465. };
  85466. impostors.forEach(function (i) {
  85467. if (!i.object.rotationQuaternion) {
  85468. return;
  85469. }
  85470. //get the correct bounding box
  85471. var oldQuaternion = i.object.rotationQuaternion;
  85472. var rot = oldQuaternion.toEulerAngles();
  85473. var extendSize = i.getObjectExtendSize();
  85474. var radToDeg = 57.295779513082320876;
  85475. if (i === impostor) {
  85476. var center = impostor.getObjectCenter();
  85477. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  85478. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  85479. //Can also use Array.prototype.push.apply
  85480. bodyConfig.pos.push(center.x);
  85481. bodyConfig.pos.push(center.y);
  85482. bodyConfig.pos.push(center.z);
  85483. bodyConfig.posShape.push(0, 0, 0);
  85484. //tmp solution
  85485. bodyConfig.rot.push(rot.x * radToDeg);
  85486. bodyConfig.rot.push(rot.y * radToDeg);
  85487. bodyConfig.rot.push(rot.z * radToDeg);
  85488. bodyConfig.rotShape.push(0, 0, 0);
  85489. }
  85490. else {
  85491. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  85492. bodyConfig.posShape.push(localPosition.x);
  85493. bodyConfig.posShape.push(localPosition.y);
  85494. bodyConfig.posShape.push(localPosition.z);
  85495. bodyConfig.pos.push(0, 0, 0);
  85496. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  85497. bodyConfig.rot.push(0);
  85498. bodyConfig.rot.push(0);
  85499. bodyConfig.rot.push(0);
  85500. bodyConfig.rotShape.push(rot.x * radToDeg);
  85501. bodyConfig.rotShape.push(rot.y * radToDeg);
  85502. bodyConfig.rotShape.push(rot.z * radToDeg);
  85503. }
  85504. // register mesh
  85505. switch (i.type) {
  85506. case BABYLON.PhysicsImpostor.ParticleImpostor:
  85507. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  85508. case BABYLON.PhysicsImpostor.SphereImpostor:
  85509. var radiusX = extendSize.x;
  85510. var radiusY = extendSize.y;
  85511. var radiusZ = extendSize.z;
  85512. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  85513. bodyConfig.type.push('sphere');
  85514. //due to the way oimo works with compounds, add 3 times
  85515. bodyConfig.size.push(size);
  85516. bodyConfig.size.push(size);
  85517. bodyConfig.size.push(size);
  85518. break;
  85519. case BABYLON.PhysicsImpostor.CylinderImpostor:
  85520. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  85521. var sizeY = checkWithEpsilon_1(extendSize.y);
  85522. bodyConfig.type.push('cylinder');
  85523. bodyConfig.size.push(sizeX);
  85524. bodyConfig.size.push(sizeY);
  85525. //due to the way oimo works with compounds, add one more value.
  85526. bodyConfig.size.push(sizeY);
  85527. break;
  85528. case BABYLON.PhysicsImpostor.PlaneImpostor:
  85529. case BABYLON.PhysicsImpostor.BoxImpostor:
  85530. default:
  85531. var sizeX = checkWithEpsilon_1(extendSize.x);
  85532. var sizeY = checkWithEpsilon_1(extendSize.y);
  85533. var sizeZ = checkWithEpsilon_1(extendSize.z);
  85534. bodyConfig.type.push('box');
  85535. //if (i === impostor) {
  85536. bodyConfig.size.push(sizeX);
  85537. bodyConfig.size.push(sizeY);
  85538. bodyConfig.size.push(sizeZ);
  85539. //} else {
  85540. // bodyConfig.size.push(0,0,0);
  85541. //}
  85542. break;
  85543. }
  85544. //actually not needed, but hey...
  85545. i.object.rotationQuaternion = oldQuaternion;
  85546. });
  85547. impostor.physicsBody = this.world.add(bodyConfig);
  85548. }
  85549. else {
  85550. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  85551. }
  85552. impostor.setDeltaPosition(this._tmpPositionVector);
  85553. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  85554. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  85555. };
  85556. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  85557. //impostor.physicsBody.dispose();
  85558. //Same as : (older oimo versions)
  85559. this.world.removeRigidBody(impostor.physicsBody);
  85560. };
  85561. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  85562. var mainBody = impostorJoint.mainImpostor.physicsBody;
  85563. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  85564. if (!mainBody || !connectedBody) {
  85565. return;
  85566. }
  85567. var jointData = impostorJoint.joint.jointData;
  85568. var options = jointData.nativeParams || {};
  85569. var type;
  85570. var nativeJointData = {
  85571. body1: mainBody,
  85572. body2: connectedBody,
  85573. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  85574. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  85575. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  85576. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  85577. min: options.min,
  85578. max: options.max,
  85579. collision: options.collision || jointData.collision,
  85580. spring: options.spring,
  85581. //supporting older version of Oimo
  85582. world: this.world
  85583. };
  85584. switch (impostorJoint.joint.type) {
  85585. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  85586. type = "jointBall";
  85587. break;
  85588. case BABYLON.PhysicsJoint.SpringJoint:
  85589. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  85590. var springData = jointData;
  85591. nativeJointData.min = springData.length || nativeJointData.min;
  85592. //Max should also be set, just make sure it is at least min
  85593. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  85594. case BABYLON.PhysicsJoint.DistanceJoint:
  85595. type = "jointDistance";
  85596. nativeJointData.max = jointData.maxDistance;
  85597. break;
  85598. case BABYLON.PhysicsJoint.PrismaticJoint:
  85599. type = "jointPrisme";
  85600. break;
  85601. case BABYLON.PhysicsJoint.SliderJoint:
  85602. type = "jointSlide";
  85603. break;
  85604. case BABYLON.PhysicsJoint.WheelJoint:
  85605. type = "jointWheel";
  85606. break;
  85607. case BABYLON.PhysicsJoint.HingeJoint:
  85608. default:
  85609. type = "jointHinge";
  85610. break;
  85611. }
  85612. nativeJointData.type = type;
  85613. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  85614. };
  85615. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  85616. //Bug in Oimo prevents us from disposing a joint in the playground
  85617. //joint.joint.physicsJoint.dispose();
  85618. //So we will bruteforce it!
  85619. try {
  85620. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  85621. }
  85622. catch (e) {
  85623. BABYLON.Tools.Warn(e);
  85624. }
  85625. };
  85626. OimoJSPlugin.prototype.isSupported = function () {
  85627. return this.BJSOIMO !== undefined;
  85628. };
  85629. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  85630. if (!impostor.physicsBody.sleeping) {
  85631. //TODO check that
  85632. /*if (impostor.physicsBody.shapes.next) {
  85633. var parentShape = this._getLastShape(impostor.physicsBody);
  85634. impostor.object.position.copyFrom(parentShape.position);
  85635. console.log(parentShape.position);
  85636. } else {*/
  85637. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  85638. //}
  85639. if (impostor.object.rotationQuaternion) {
  85640. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  85641. }
  85642. }
  85643. };
  85644. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  85645. var body = impostor.physicsBody;
  85646. body.position.copy(newPosition);
  85647. body.orientation.copy(newRotation);
  85648. body.syncShapes();
  85649. body.awake();
  85650. };
  85651. /*private _getLastShape(body: any): any {
  85652. var lastShape = body.shapes;
  85653. while (lastShape.next) {
  85654. lastShape = lastShape.next;
  85655. }
  85656. return lastShape;
  85657. }*/
  85658. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  85659. impostor.physicsBody.linearVelocity.copy(velocity);
  85660. };
  85661. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  85662. impostor.physicsBody.angularVelocity.copy(velocity);
  85663. };
  85664. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  85665. var v = impostor.physicsBody.linearVelocity;
  85666. if (!v) {
  85667. return null;
  85668. }
  85669. return new BABYLON.Vector3(v.x, v.y, v.z);
  85670. };
  85671. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  85672. var v = impostor.physicsBody.angularVelocity;
  85673. if (!v) {
  85674. return null;
  85675. }
  85676. return new BABYLON.Vector3(v.x, v.y, v.z);
  85677. };
  85678. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  85679. var staticBody = mass === 0;
  85680. //this will actually set the body's density and not its mass.
  85681. //But this is how oimo treats the mass variable.
  85682. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  85683. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  85684. };
  85685. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  85686. return impostor.physicsBody.shapes.density;
  85687. };
  85688. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  85689. return impostor.physicsBody.shapes.friction;
  85690. };
  85691. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  85692. impostor.physicsBody.shapes.friction = friction;
  85693. };
  85694. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  85695. return impostor.physicsBody.shapes.restitution;
  85696. };
  85697. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  85698. impostor.physicsBody.shapes.restitution = restitution;
  85699. };
  85700. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  85701. impostor.physicsBody.sleep();
  85702. };
  85703. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  85704. impostor.physicsBody.awake();
  85705. };
  85706. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  85707. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  85708. if (minDistance !== void 0) {
  85709. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  85710. }
  85711. };
  85712. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  85713. //TODO separate rotational and transational motors.
  85714. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  85715. if (motor) {
  85716. motor.setMotor(speed, maxForce);
  85717. }
  85718. };
  85719. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  85720. //TODO separate rotational and transational motors.
  85721. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  85722. if (motor) {
  85723. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  85724. }
  85725. };
  85726. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  85727. var body = impostor.physicsBody;
  85728. mesh.position.x = body.position.x;
  85729. mesh.position.y = body.position.y;
  85730. mesh.position.z = body.position.z;
  85731. if (mesh.rotationQuaternion) {
  85732. mesh.rotationQuaternion.x = body.orientation.x;
  85733. mesh.rotationQuaternion.y = body.orientation.y;
  85734. mesh.rotationQuaternion.z = body.orientation.z;
  85735. mesh.rotationQuaternion.w = body.orientation.s;
  85736. }
  85737. };
  85738. OimoJSPlugin.prototype.getRadius = function (impostor) {
  85739. return impostor.physicsBody.shapes.radius;
  85740. };
  85741. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  85742. var shape = impostor.physicsBody.shapes;
  85743. result.x = shape.halfWidth * 2;
  85744. result.y = shape.halfHeight * 2;
  85745. result.z = shape.halfDepth * 2;
  85746. };
  85747. OimoJSPlugin.prototype.dispose = function () {
  85748. this.world.clear();
  85749. };
  85750. return OimoJSPlugin;
  85751. }());
  85752. BABYLON.OimoJSPlugin = OimoJSPlugin;
  85753. })(BABYLON || (BABYLON = {}));
  85754. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  85755. var BABYLON;
  85756. (function (BABYLON) {
  85757. /*
  85758. * Based on jsTGALoader - Javascript loader for TGA file
  85759. * By Vincent Thibault
  85760. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  85761. */
  85762. var TGATools = /** @class */ (function () {
  85763. function TGATools() {
  85764. }
  85765. TGATools.GetTGAHeader = function (data) {
  85766. var offset = 0;
  85767. var header = {
  85768. id_length: data[offset++],
  85769. colormap_type: data[offset++],
  85770. image_type: data[offset++],
  85771. colormap_index: data[offset++] | data[offset++] << 8,
  85772. colormap_length: data[offset++] | data[offset++] << 8,
  85773. colormap_size: data[offset++],
  85774. origin: [
  85775. data[offset++] | data[offset++] << 8,
  85776. data[offset++] | data[offset++] << 8
  85777. ],
  85778. width: data[offset++] | data[offset++] << 8,
  85779. height: data[offset++] | data[offset++] << 8,
  85780. pixel_size: data[offset++],
  85781. flags: data[offset++]
  85782. };
  85783. return header;
  85784. };
  85785. TGATools.UploadContent = function (gl, data) {
  85786. // Not enough data to contain header ?
  85787. if (data.length < 19) {
  85788. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  85789. return;
  85790. }
  85791. // Read Header
  85792. var offset = 18;
  85793. var header = TGATools.GetTGAHeader(data);
  85794. // Assume it's a valid Targa file.
  85795. if (header.id_length + offset > data.length) {
  85796. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  85797. return;
  85798. }
  85799. // Skip not needed data
  85800. offset += header.id_length;
  85801. var use_rle = false;
  85802. var use_pal = false;
  85803. var use_grey = false;
  85804. // Get some informations.
  85805. switch (header.image_type) {
  85806. case TGATools._TYPE_RLE_INDEXED:
  85807. use_rle = true;
  85808. case TGATools._TYPE_INDEXED:
  85809. use_pal = true;
  85810. break;
  85811. case TGATools._TYPE_RLE_RGB:
  85812. use_rle = true;
  85813. case TGATools._TYPE_RGB:
  85814. // use_rgb = true;
  85815. break;
  85816. case TGATools._TYPE_RLE_GREY:
  85817. use_rle = true;
  85818. case TGATools._TYPE_GREY:
  85819. use_grey = true;
  85820. break;
  85821. }
  85822. var pixel_data;
  85823. // var numAlphaBits = header.flags & 0xf;
  85824. var pixel_size = header.pixel_size >> 3;
  85825. var pixel_total = header.width * header.height * pixel_size;
  85826. // Read palettes
  85827. var palettes;
  85828. if (use_pal) {
  85829. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  85830. }
  85831. // Read LRE
  85832. if (use_rle) {
  85833. pixel_data = new Uint8Array(pixel_total);
  85834. var c, count, i;
  85835. var localOffset = 0;
  85836. var pixels = new Uint8Array(pixel_size);
  85837. while (offset < pixel_total && localOffset < pixel_total) {
  85838. c = data[offset++];
  85839. count = (c & 0x7f) + 1;
  85840. // RLE pixels
  85841. if (c & 0x80) {
  85842. // Bind pixel tmp array
  85843. for (i = 0; i < pixel_size; ++i) {
  85844. pixels[i] = data[offset++];
  85845. }
  85846. // Copy pixel array
  85847. for (i = 0; i < count; ++i) {
  85848. pixel_data.set(pixels, localOffset + i * pixel_size);
  85849. }
  85850. localOffset += pixel_size * count;
  85851. }
  85852. // Raw pixels
  85853. else {
  85854. count *= pixel_size;
  85855. for (i = 0; i < count; ++i) {
  85856. pixel_data[localOffset + i] = data[offset++];
  85857. }
  85858. localOffset += count;
  85859. }
  85860. }
  85861. }
  85862. // RAW Pixels
  85863. else {
  85864. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  85865. }
  85866. // Load to texture
  85867. var x_start, y_start, x_step, y_step, y_end, x_end;
  85868. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  85869. default:
  85870. case TGATools._ORIGIN_UL:
  85871. x_start = 0;
  85872. x_step = 1;
  85873. x_end = header.width;
  85874. y_start = 0;
  85875. y_step = 1;
  85876. y_end = header.height;
  85877. break;
  85878. case TGATools._ORIGIN_BL:
  85879. x_start = 0;
  85880. x_step = 1;
  85881. x_end = header.width;
  85882. y_start = header.height - 1;
  85883. y_step = -1;
  85884. y_end = -1;
  85885. break;
  85886. case TGATools._ORIGIN_UR:
  85887. x_start = header.width - 1;
  85888. x_step = -1;
  85889. x_end = -1;
  85890. y_start = 0;
  85891. y_step = 1;
  85892. y_end = header.height;
  85893. break;
  85894. case TGATools._ORIGIN_BR:
  85895. x_start = header.width - 1;
  85896. x_step = -1;
  85897. x_end = -1;
  85898. y_start = header.height - 1;
  85899. y_step = -1;
  85900. y_end = -1;
  85901. break;
  85902. }
  85903. // Load the specify method
  85904. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  85905. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  85906. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  85907. };
  85908. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85909. var image = pixel_data, colormap = palettes;
  85910. var width = header.width, height = header.height;
  85911. var color, i = 0, x, y;
  85912. var imageData = new Uint8Array(width * height * 4);
  85913. for (y = y_start; y !== y_end; y += y_step) {
  85914. for (x = x_start; x !== x_end; x += x_step, i++) {
  85915. color = image[i];
  85916. imageData[(x + width * y) * 4 + 3] = 255;
  85917. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  85918. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  85919. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  85920. }
  85921. }
  85922. return imageData;
  85923. };
  85924. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85925. var image = pixel_data;
  85926. var width = header.width, height = header.height;
  85927. var color, i = 0, x, y;
  85928. var imageData = new Uint8Array(width * height * 4);
  85929. for (y = y_start; y !== y_end; y += y_step) {
  85930. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  85931. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  85932. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  85933. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  85934. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  85935. imageData[(x + width * y) * 4 + 0] = r;
  85936. imageData[(x + width * y) * 4 + 1] = g;
  85937. imageData[(x + width * y) * 4 + 2] = b;
  85938. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  85939. }
  85940. }
  85941. return imageData;
  85942. };
  85943. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85944. var image = pixel_data;
  85945. var width = header.width, height = header.height;
  85946. var i = 0, x, y;
  85947. var imageData = new Uint8Array(width * height * 4);
  85948. for (y = y_start; y !== y_end; y += y_step) {
  85949. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  85950. imageData[(x + width * y) * 4 + 3] = 255;
  85951. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  85952. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  85953. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  85954. }
  85955. }
  85956. return imageData;
  85957. };
  85958. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85959. var image = pixel_data;
  85960. var width = header.width, height = header.height;
  85961. var i = 0, x, y;
  85962. var imageData = new Uint8Array(width * height * 4);
  85963. for (y = y_start; y !== y_end; y += y_step) {
  85964. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  85965. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  85966. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  85967. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  85968. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  85969. }
  85970. }
  85971. return imageData;
  85972. };
  85973. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85974. var image = pixel_data;
  85975. var width = header.width, height = header.height;
  85976. var color, i = 0, x, y;
  85977. var imageData = new Uint8Array(width * height * 4);
  85978. for (y = y_start; y !== y_end; y += y_step) {
  85979. for (x = x_start; x !== x_end; x += x_step, i++) {
  85980. color = image[i];
  85981. imageData[(x + width * y) * 4 + 0] = color;
  85982. imageData[(x + width * y) * 4 + 1] = color;
  85983. imageData[(x + width * y) * 4 + 2] = color;
  85984. imageData[(x + width * y) * 4 + 3] = 255;
  85985. }
  85986. }
  85987. return imageData;
  85988. };
  85989. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85990. var image = pixel_data;
  85991. var width = header.width, height = header.height;
  85992. var i = 0, x, y;
  85993. var imageData = new Uint8Array(width * height * 4);
  85994. for (y = y_start; y !== y_end; y += y_step) {
  85995. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  85996. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  85997. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  85998. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  85999. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  86000. }
  86001. }
  86002. return imageData;
  86003. };
  86004. //private static _TYPE_NO_DATA = 0;
  86005. TGATools._TYPE_INDEXED = 1;
  86006. TGATools._TYPE_RGB = 2;
  86007. TGATools._TYPE_GREY = 3;
  86008. TGATools._TYPE_RLE_INDEXED = 9;
  86009. TGATools._TYPE_RLE_RGB = 10;
  86010. TGATools._TYPE_RLE_GREY = 11;
  86011. TGATools._ORIGIN_MASK = 0x30;
  86012. TGATools._ORIGIN_SHIFT = 0x04;
  86013. TGATools._ORIGIN_BL = 0x00;
  86014. TGATools._ORIGIN_BR = 0x01;
  86015. TGATools._ORIGIN_UL = 0x02;
  86016. TGATools._ORIGIN_UR = 0x03;
  86017. return TGATools;
  86018. }());
  86019. BABYLON.TGATools = TGATools;
  86020. })(BABYLON || (BABYLON = {}));
  86021. //# sourceMappingURL=babylon.tga.js.map
  86022. var BABYLON;
  86023. (function (BABYLON) {
  86024. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  86025. // All values and structures referenced from:
  86026. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  86027. var DDS_MAGIC = 0x20534444;
  86028. var
  86029. //DDSD_CAPS = 0x1,
  86030. //DDSD_HEIGHT = 0x2,
  86031. //DDSD_WIDTH = 0x4,
  86032. //DDSD_PITCH = 0x8,
  86033. //DDSD_PIXELFORMAT = 0x1000,
  86034. DDSD_MIPMAPCOUNT = 0x20000;
  86035. //DDSD_LINEARSIZE = 0x80000,
  86036. //DDSD_DEPTH = 0x800000;
  86037. // var DDSCAPS_COMPLEX = 0x8,
  86038. // DDSCAPS_MIPMAP = 0x400000,
  86039. // DDSCAPS_TEXTURE = 0x1000;
  86040. var DDSCAPS2_CUBEMAP = 0x200;
  86041. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  86042. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  86043. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  86044. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  86045. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  86046. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  86047. // DDSCAPS2_VOLUME = 0x200000;
  86048. var
  86049. //DDPF_ALPHAPIXELS = 0x1,
  86050. //DDPF_ALPHA = 0x2,
  86051. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  86052. //DDPF_YUV = 0x200,
  86053. DDPF_LUMINANCE = 0x20000;
  86054. function FourCCToInt32(value) {
  86055. return value.charCodeAt(0) +
  86056. (value.charCodeAt(1) << 8) +
  86057. (value.charCodeAt(2) << 16) +
  86058. (value.charCodeAt(3) << 24);
  86059. }
  86060. function Int32ToFourCC(value) {
  86061. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  86062. }
  86063. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  86064. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  86065. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  86066. var FOURCC_DX10 = FourCCToInt32("DX10");
  86067. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  86068. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  86069. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  86070. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  86071. var headerLengthInt = 31; // The header length in 32 bit ints
  86072. // Offsets into the header array
  86073. var off_magic = 0;
  86074. var off_size = 1;
  86075. var off_flags = 2;
  86076. var off_height = 3;
  86077. var off_width = 4;
  86078. var off_mipmapCount = 7;
  86079. var off_pfFlags = 20;
  86080. var off_pfFourCC = 21;
  86081. var off_RGBbpp = 22;
  86082. var off_RMask = 23;
  86083. var off_GMask = 24;
  86084. var off_BMask = 25;
  86085. var off_AMask = 26;
  86086. // var off_caps1 = 27;
  86087. var off_caps2 = 28;
  86088. // var off_caps3 = 29;
  86089. // var off_caps4 = 30;
  86090. var off_dxgiFormat = 32;
  86091. ;
  86092. var DDSTools = /** @class */ (function () {
  86093. function DDSTools() {
  86094. }
  86095. DDSTools.GetDDSInfo = function (arrayBuffer) {
  86096. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  86097. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  86098. var mipmapCount = 1;
  86099. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  86100. mipmapCount = Math.max(1, header[off_mipmapCount]);
  86101. }
  86102. var fourCC = header[off_pfFourCC];
  86103. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  86104. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86105. switch (fourCC) {
  86106. case FOURCC_D3DFMT_R16G16B16A16F:
  86107. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86108. break;
  86109. case FOURCC_D3DFMT_R32G32B32A32F:
  86110. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  86111. break;
  86112. case FOURCC_DX10:
  86113. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  86114. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86115. break;
  86116. }
  86117. }
  86118. return {
  86119. width: header[off_width],
  86120. height: header[off_height],
  86121. mipmapCount: mipmapCount,
  86122. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  86123. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  86124. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  86125. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  86126. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  86127. dxgiFormat: dxgiFormat,
  86128. textureType: textureType
  86129. };
  86130. };
  86131. DDSTools._ToHalfFloat = function (value) {
  86132. if (!DDSTools._FloatView) {
  86133. DDSTools._FloatView = new Float32Array(1);
  86134. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  86135. }
  86136. DDSTools._FloatView[0] = value;
  86137. var x = DDSTools._Int32View[0];
  86138. var bits = (x >> 16) & 0x8000; /* Get the sign */
  86139. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  86140. var e = (x >> 23) & 0xff; /* Using int is faster here */
  86141. /* If zero, or denormal, or exponent underflows too much for a denormal
  86142. * half, return signed zero. */
  86143. if (e < 103) {
  86144. return bits;
  86145. }
  86146. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  86147. if (e > 142) {
  86148. bits |= 0x7c00;
  86149. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  86150. * not Inf, so make sure we set one mantissa bit too. */
  86151. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  86152. return bits;
  86153. }
  86154. /* If exponent underflows but not too much, return a denormal */
  86155. if (e < 113) {
  86156. m |= 0x0800;
  86157. /* Extra rounding may overflow and set mantissa to 0 and exponent
  86158. * to 1, which is OK. */
  86159. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  86160. return bits;
  86161. }
  86162. bits |= ((e - 112) << 10) | (m >> 1);
  86163. bits += m & 1;
  86164. return bits;
  86165. };
  86166. DDSTools._FromHalfFloat = function (value) {
  86167. var s = (value & 0x8000) >> 15;
  86168. var e = (value & 0x7C00) >> 10;
  86169. var f = value & 0x03FF;
  86170. if (e === 0) {
  86171. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  86172. }
  86173. else if (e == 0x1F) {
  86174. return f ? NaN : ((s ? -1 : 1) * Infinity);
  86175. }
  86176. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  86177. };
  86178. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86179. var destArray = new Float32Array(dataLength);
  86180. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  86181. var index = 0;
  86182. for (var y = 0; y < height; y++) {
  86183. for (var x = 0; x < width; x++) {
  86184. var srcPos = (x + y * width) * 4;
  86185. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  86186. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  86187. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  86188. if (DDSTools.StoreLODInAlphaChannel) {
  86189. destArray[index + 3] = lod;
  86190. }
  86191. else {
  86192. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  86193. }
  86194. index += 4;
  86195. }
  86196. }
  86197. return destArray;
  86198. };
  86199. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86200. if (DDSTools.StoreLODInAlphaChannel) {
  86201. var destArray = new Uint16Array(dataLength);
  86202. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  86203. var index = 0;
  86204. for (var y = 0; y < height; y++) {
  86205. for (var x = 0; x < width; x++) {
  86206. var srcPos = (x + y * width) * 4;
  86207. destArray[index] = srcData[srcPos];
  86208. destArray[index + 1] = srcData[srcPos + 1];
  86209. destArray[index + 2] = srcData[srcPos + 2];
  86210. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  86211. index += 4;
  86212. }
  86213. }
  86214. return destArray;
  86215. }
  86216. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  86217. };
  86218. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86219. if (DDSTools.StoreLODInAlphaChannel) {
  86220. var destArray = new Float32Array(dataLength);
  86221. var srcData = new Float32Array(arrayBuffer, dataOffset);
  86222. var index = 0;
  86223. for (var y = 0; y < height; y++) {
  86224. for (var x = 0; x < width; x++) {
  86225. var srcPos = (x + y * width) * 4;
  86226. destArray[index] = srcData[srcPos];
  86227. destArray[index + 1] = srcData[srcPos + 1];
  86228. destArray[index + 2] = srcData[srcPos + 2];
  86229. destArray[index + 3] = lod;
  86230. index += 4;
  86231. }
  86232. }
  86233. return destArray;
  86234. }
  86235. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  86236. };
  86237. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86238. var destArray = new Uint8Array(dataLength);
  86239. var srcData = new Float32Array(arrayBuffer, dataOffset);
  86240. var index = 0;
  86241. for (var y = 0; y < height; y++) {
  86242. for (var x = 0; x < width; x++) {
  86243. var srcPos = (x + y * width) * 4;
  86244. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  86245. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  86246. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  86247. if (DDSTools.StoreLODInAlphaChannel) {
  86248. destArray[index + 3] = lod;
  86249. }
  86250. else {
  86251. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  86252. }
  86253. index += 4;
  86254. }
  86255. }
  86256. return destArray;
  86257. };
  86258. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86259. var destArray = new Uint8Array(dataLength);
  86260. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  86261. var index = 0;
  86262. for (var y = 0; y < height; y++) {
  86263. for (var x = 0; x < width; x++) {
  86264. var srcPos = (x + y * width) * 4;
  86265. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  86266. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  86267. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  86268. if (DDSTools.StoreLODInAlphaChannel) {
  86269. destArray[index + 3] = lod;
  86270. }
  86271. else {
  86272. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  86273. }
  86274. index += 4;
  86275. }
  86276. }
  86277. return destArray;
  86278. };
  86279. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  86280. var byteArray = new Uint8Array(dataLength);
  86281. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  86282. var index = 0;
  86283. for (var y = 0; y < height; y++) {
  86284. for (var x = 0; x < width; x++) {
  86285. var srcPos = (x + y * width) * 4;
  86286. byteArray[index] = srcData[srcPos + rOffset];
  86287. byteArray[index + 1] = srcData[srcPos + gOffset];
  86288. byteArray[index + 2] = srcData[srcPos + bOffset];
  86289. byteArray[index + 3] = srcData[srcPos + aOffset];
  86290. index += 4;
  86291. }
  86292. }
  86293. return byteArray;
  86294. };
  86295. DDSTools._ExtractLongWordOrder = function (value) {
  86296. if (value === 0 || value === 255 || value === -16777216) {
  86297. return 0;
  86298. }
  86299. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  86300. };
  86301. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  86302. var byteArray = new Uint8Array(dataLength);
  86303. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  86304. var index = 0;
  86305. for (var y = 0; y < height; y++) {
  86306. for (var x = 0; x < width; x++) {
  86307. var srcPos = (x + y * width) * 3;
  86308. byteArray[index] = srcData[srcPos + rOffset];
  86309. byteArray[index + 1] = srcData[srcPos + gOffset];
  86310. byteArray[index + 2] = srcData[srcPos + bOffset];
  86311. index += 3;
  86312. }
  86313. }
  86314. return byteArray;
  86315. };
  86316. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  86317. var byteArray = new Uint8Array(dataLength);
  86318. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  86319. var index = 0;
  86320. for (var y = 0; y < height; y++) {
  86321. for (var x = 0; x < width; x++) {
  86322. var srcPos = (x + y * width);
  86323. byteArray[index] = srcData[srcPos];
  86324. index++;
  86325. }
  86326. }
  86327. return byteArray;
  86328. };
  86329. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  86330. if (lodIndex === void 0) { lodIndex = -1; }
  86331. var sphericalPolynomialFaces = null;
  86332. if (info.sphericalPolynomial) {
  86333. sphericalPolynomialFaces = new Array();
  86334. }
  86335. var ext = engine.getCaps().s3tc;
  86336. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  86337. var fourCC, width, height, dataLength = 0, dataOffset;
  86338. var byteArray, mipmapCount, mip;
  86339. var internalFormat = 0;
  86340. var format = 0;
  86341. var blockBytes = 1;
  86342. if (header[off_magic] !== DDS_MAGIC) {
  86343. BABYLON.Tools.Error("Invalid magic number in DDS header");
  86344. return;
  86345. }
  86346. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  86347. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  86348. return;
  86349. }
  86350. if (info.isCompressed && !ext) {
  86351. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  86352. return;
  86353. }
  86354. var bpp = header[off_RGBbpp];
  86355. dataOffset = header[off_size] + 4;
  86356. var computeFormats = false;
  86357. if (info.isFourCC) {
  86358. fourCC = header[off_pfFourCC];
  86359. switch (fourCC) {
  86360. case FOURCC_DXT1:
  86361. blockBytes = 8;
  86362. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  86363. break;
  86364. case FOURCC_DXT3:
  86365. blockBytes = 16;
  86366. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  86367. break;
  86368. case FOURCC_DXT5:
  86369. blockBytes = 16;
  86370. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  86371. break;
  86372. case FOURCC_D3DFMT_R16G16B16A16F:
  86373. computeFormats = true;
  86374. break;
  86375. case FOURCC_D3DFMT_R32G32B32A32F:
  86376. computeFormats = true;
  86377. break;
  86378. case FOURCC_DX10:
  86379. // There is an additionnal header so dataOffset need to be changed
  86380. dataOffset += 5 * 4; // 5 uints
  86381. var supported = false;
  86382. switch (info.dxgiFormat) {
  86383. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  86384. computeFormats = true;
  86385. supported = true;
  86386. break;
  86387. case DXGI_FORMAT_B8G8R8X8_UNORM:
  86388. info.isRGB = true;
  86389. info.isFourCC = false;
  86390. bpp = 32;
  86391. supported = true;
  86392. break;
  86393. }
  86394. if (supported) {
  86395. break;
  86396. }
  86397. default:
  86398. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  86399. return;
  86400. }
  86401. }
  86402. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  86403. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  86404. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  86405. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  86406. if (computeFormats) {
  86407. format = engine._getWebGLTextureType(info.textureType);
  86408. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86409. }
  86410. mipmapCount = 1;
  86411. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  86412. mipmapCount = Math.max(1, header[off_mipmapCount]);
  86413. }
  86414. for (var face = 0; face < faces; face++) {
  86415. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  86416. width = header[off_width];
  86417. height = header[off_height];
  86418. for (mip = 0; mip < mipmapCount; ++mip) {
  86419. if (lodIndex === -1 || lodIndex === mip) {
  86420. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  86421. var i = (lodIndex === -1) ? mip : 0;
  86422. if (!info.isCompressed && info.isFourCC) {
  86423. dataLength = width * height * 4;
  86424. var floatArray = null;
  86425. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  86426. if (bpp === 128) {
  86427. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86428. if (sphericalPolynomialFaces && i == 0) {
  86429. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86430. }
  86431. }
  86432. else if (bpp === 64) {
  86433. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86434. if (sphericalPolynomialFaces && i == 0) {
  86435. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86436. }
  86437. }
  86438. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86439. format = engine._getWebGLTextureType(info.textureType);
  86440. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86441. }
  86442. else {
  86443. if (bpp === 128) {
  86444. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86445. if (sphericalPolynomialFaces && i == 0) {
  86446. sphericalPolynomialFaces.push(floatArray);
  86447. }
  86448. }
  86449. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  86450. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86451. if (sphericalPolynomialFaces && i == 0) {
  86452. sphericalPolynomialFaces.push(floatArray);
  86453. }
  86454. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  86455. format = engine._getWebGLTextureType(info.textureType);
  86456. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86457. }
  86458. else { // 64
  86459. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86460. if (sphericalPolynomialFaces && i == 0) {
  86461. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86462. }
  86463. }
  86464. }
  86465. if (floatArray) {
  86466. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  86467. }
  86468. }
  86469. else if (info.isRGB) {
  86470. if (bpp === 24) {
  86471. dataLength = width * height * 3;
  86472. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  86473. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  86474. }
  86475. else { // 32
  86476. dataLength = width * height * 4;
  86477. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  86478. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  86479. }
  86480. }
  86481. else if (info.isLuminance) {
  86482. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  86483. var unpaddedRowSize = width;
  86484. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  86485. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  86486. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  86487. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  86488. }
  86489. else {
  86490. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  86491. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  86492. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  86493. }
  86494. }
  86495. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  86496. width *= 0.5;
  86497. height *= 0.5;
  86498. width = Math.max(1.0, width);
  86499. height = Math.max(1.0, height);
  86500. }
  86501. if (currentFace !== undefined) {
  86502. // Loading a single face
  86503. break;
  86504. }
  86505. }
  86506. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  86507. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  86508. size: header[off_width],
  86509. right: sphericalPolynomialFaces[0],
  86510. left: sphericalPolynomialFaces[1],
  86511. up: sphericalPolynomialFaces[2],
  86512. down: sphericalPolynomialFaces[3],
  86513. front: sphericalPolynomialFaces[4],
  86514. back: sphericalPolynomialFaces[5],
  86515. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  86516. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  86517. gammaSpace: false,
  86518. });
  86519. }
  86520. else {
  86521. info.sphericalPolynomial = undefined;
  86522. }
  86523. };
  86524. DDSTools.StoreLODInAlphaChannel = false;
  86525. return DDSTools;
  86526. }());
  86527. BABYLON.DDSTools = DDSTools;
  86528. })(BABYLON || (BABYLON = {}));
  86529. //# sourceMappingURL=babylon.dds.js.map
  86530. var BABYLON;
  86531. (function (BABYLON) {
  86532. /**
  86533. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  86534. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  86535. */
  86536. var KhronosTextureContainer = /** @class */ (function () {
  86537. /**
  86538. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  86539. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  86540. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  86541. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  86542. */
  86543. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  86544. this.arrayBuffer = arrayBuffer;
  86545. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  86546. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  86547. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  86548. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  86549. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  86550. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  86551. BABYLON.Tools.Error("texture missing KTX identifier");
  86552. return;
  86553. }
  86554. // load the reset of the header in native 32 bit int
  86555. var header = new Int32Array(this.arrayBuffer, 12, 13);
  86556. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  86557. var oppositeEndianess = header[0] === 0x01020304;
  86558. // read all the header elements in order they exist in the file, without modification (sans endainness)
  86559. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  86560. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  86561. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  86562. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  86563. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  86564. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  86565. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  86566. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  86567. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  86568. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  86569. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  86570. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  86571. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  86572. if (this.glType !== 0) {
  86573. BABYLON.Tools.Error("only compressed formats currently supported");
  86574. return;
  86575. }
  86576. else {
  86577. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  86578. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  86579. }
  86580. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  86581. BABYLON.Tools.Error("only 2D textures currently supported");
  86582. return;
  86583. }
  86584. if (this.numberOfArrayElements !== 0) {
  86585. BABYLON.Tools.Error("texture arrays not currently supported");
  86586. return;
  86587. }
  86588. if (this.numberOfFaces !== facesExpected) {
  86589. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  86590. return;
  86591. }
  86592. // we now have a completely validated file, so could use existence of loadType as success
  86593. // would need to make this more elaborate & adjust checks above to support more than one load type
  86594. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  86595. }
  86596. // not as fast hardware based, but will probably never need to use
  86597. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  86598. return ((val & 0xFF) << 24)
  86599. | ((val & 0xFF00) << 8)
  86600. | ((val >> 8) & 0xFF00)
  86601. | ((val >> 24) & 0xFF);
  86602. };
  86603. /**
  86604. * It is assumed that the texture has already been created & is currently bound
  86605. */
  86606. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  86607. switch (this.loadType) {
  86608. case KhronosTextureContainer.COMPRESSED_2D:
  86609. this._upload2DCompressedLevels(gl, loadMipmaps);
  86610. break;
  86611. case KhronosTextureContainer.TEX_2D:
  86612. case KhronosTextureContainer.COMPRESSED_3D:
  86613. case KhronosTextureContainer.TEX_3D:
  86614. }
  86615. };
  86616. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  86617. // initialize width & height for level 1
  86618. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  86619. var width = this.pixelWidth;
  86620. var height = this.pixelHeight;
  86621. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  86622. for (var level = 0; level < mipmapCount; level++) {
  86623. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  86624. for (var face = 0; face < this.numberOfFaces; face++) {
  86625. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  86626. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  86627. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  86628. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  86629. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  86630. }
  86631. width = Math.max(1.0, width * 0.5);
  86632. height = Math.max(1.0, height * 0.5);
  86633. }
  86634. };
  86635. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  86636. // load types
  86637. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  86638. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  86639. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  86640. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  86641. return KhronosTextureContainer;
  86642. }());
  86643. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  86644. })(BABYLON || (BABYLON = {}));
  86645. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  86646. var BABYLON;
  86647. (function (BABYLON) {
  86648. var Debug;
  86649. (function (Debug) {
  86650. /**
  86651. * Class used to render a debug view of a given skeleton
  86652. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  86653. */
  86654. var SkeletonViewer = /** @class */ (function () {
  86655. /**
  86656. * Creates a new SkeletonViewer
  86657. * @param skeleton defines the skeleton to render
  86658. * @param mesh defines the mesh attached to the skeleton
  86659. * @param scene defines the hosting scene
  86660. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  86661. * @param renderingGroupId defines the rendering group id to use with the viewer
  86662. */
  86663. function SkeletonViewer(
  86664. /** defines the skeleton to render */
  86665. skeleton,
  86666. /** defines the mesh attached to the skeleton */
  86667. mesh, scene,
  86668. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  86669. autoUpdateBonesMatrices,
  86670. /** defines the rendering group id to use with the viewer */
  86671. renderingGroupId) {
  86672. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  86673. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  86674. this.skeleton = skeleton;
  86675. this.mesh = mesh;
  86676. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  86677. this.renderingGroupId = renderingGroupId;
  86678. /** Gets or sets the color used to render the skeleton */
  86679. this.color = BABYLON.Color3.White();
  86680. this._debugLines = new Array();
  86681. this._isEnabled = false;
  86682. this._scene = scene;
  86683. this.update();
  86684. this._renderFunction = this.update.bind(this);
  86685. }
  86686. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  86687. get: function () {
  86688. return this._isEnabled;
  86689. },
  86690. /** Gets or sets a boolean indicating if the viewer is enabled */
  86691. set: function (value) {
  86692. if (this._isEnabled === value) {
  86693. return;
  86694. }
  86695. this._isEnabled = value;
  86696. if (value) {
  86697. this._scene.registerBeforeRender(this._renderFunction);
  86698. }
  86699. else {
  86700. this._scene.unregisterBeforeRender(this._renderFunction);
  86701. }
  86702. },
  86703. enumerable: true,
  86704. configurable: true
  86705. });
  86706. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  86707. if (x === void 0) { x = 0; }
  86708. if (y === void 0) { y = 0; }
  86709. if (z === void 0) { z = 0; }
  86710. var tmat = BABYLON.Tmp.Matrix[0];
  86711. var parentBone = bone.getParent();
  86712. tmat.copyFrom(bone.getLocalMatrix());
  86713. if (x !== 0 || y !== 0 || z !== 0) {
  86714. var tmat2 = BABYLON.Tmp.Matrix[1];
  86715. BABYLON.Matrix.IdentityToRef(tmat2);
  86716. tmat2.m[12] = x;
  86717. tmat2.m[13] = y;
  86718. tmat2.m[14] = z;
  86719. tmat2.multiplyToRef(tmat, tmat);
  86720. }
  86721. if (parentBone) {
  86722. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  86723. }
  86724. tmat.multiplyToRef(meshMat, tmat);
  86725. position.x = tmat.m[12];
  86726. position.y = tmat.m[13];
  86727. position.z = tmat.m[14];
  86728. };
  86729. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  86730. var len = bones.length;
  86731. var meshPos = this.mesh.position;
  86732. for (var i = 0; i < len; i++) {
  86733. var bone = bones[i];
  86734. var points = this._debugLines[i];
  86735. if (!points) {
  86736. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86737. this._debugLines[i] = points;
  86738. }
  86739. this._getBonePosition(points[0], bone, meshMat);
  86740. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  86741. points[0].subtractInPlace(meshPos);
  86742. points[1].subtractInPlace(meshPos);
  86743. }
  86744. };
  86745. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  86746. var len = bones.length;
  86747. var boneNum = 0;
  86748. var meshPos = this.mesh.position;
  86749. for (var i = len - 1; i >= 0; i--) {
  86750. var childBone = bones[i];
  86751. var parentBone = childBone.getParent();
  86752. if (!parentBone) {
  86753. continue;
  86754. }
  86755. var points = this._debugLines[boneNum];
  86756. if (!points) {
  86757. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86758. this._debugLines[boneNum] = points;
  86759. }
  86760. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  86761. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  86762. points[0].subtractInPlace(meshPos);
  86763. points[1].subtractInPlace(meshPos);
  86764. boneNum++;
  86765. }
  86766. };
  86767. /** Update the viewer to sync with current skeleton state */
  86768. SkeletonViewer.prototype.update = function () {
  86769. if (this.autoUpdateBonesMatrices) {
  86770. this.skeleton.computeAbsoluteTransforms();
  86771. }
  86772. if (this.skeleton.bones[0].length === undefined) {
  86773. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  86774. }
  86775. else {
  86776. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  86777. }
  86778. if (!this._debugMesh) {
  86779. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  86780. this._debugMesh.renderingGroupId = this.renderingGroupId;
  86781. }
  86782. else {
  86783. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  86784. }
  86785. this._debugMesh.position.copyFrom(this.mesh.position);
  86786. this._debugMesh.color = this.color;
  86787. };
  86788. /** Release associated resources */
  86789. SkeletonViewer.prototype.dispose = function () {
  86790. if (this._debugMesh) {
  86791. this.isEnabled = false;
  86792. this._debugMesh.dispose();
  86793. this._debugMesh = null;
  86794. }
  86795. };
  86796. return SkeletonViewer;
  86797. }());
  86798. Debug.SkeletonViewer = SkeletonViewer;
  86799. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86800. })(BABYLON || (BABYLON = {}));
  86801. //# sourceMappingURL=babylon.skeletonViewer.js.map
  86802. /**
  86803. * Module Debug contains the (visual) components to debug a scene correctly
  86804. */
  86805. var BABYLON;
  86806. (function (BABYLON) {
  86807. var Debug;
  86808. (function (Debug) {
  86809. /**
  86810. * The Axes viewer will show 3 axes in a specific point in space
  86811. */
  86812. var AxesViewer = /** @class */ (function () {
  86813. /**
  86814. * Creates a new AxesViewer
  86815. * @param scene defines the hosting scene
  86816. * @param scaleLines defines a number used to scale line length (1 by default)
  86817. */
  86818. function AxesViewer(scene, scaleLines) {
  86819. if (scaleLines === void 0) { scaleLines = 1; }
  86820. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86821. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86822. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86823. /**
  86824. * Gets or sets a number used to scale line length
  86825. */
  86826. this.scaleLines = 1;
  86827. this.scaleLines = scaleLines;
  86828. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  86829. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  86830. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  86831. this._xmesh.renderingGroupId = 2;
  86832. this._ymesh.renderingGroupId = 2;
  86833. this._zmesh.renderingGroupId = 2;
  86834. this._xmesh.material.checkReadyOnlyOnce = true;
  86835. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  86836. this._ymesh.material.checkReadyOnlyOnce = true;
  86837. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  86838. this._zmesh.material.checkReadyOnlyOnce = true;
  86839. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  86840. this.scene = scene;
  86841. }
  86842. /**
  86843. * Force the viewer to update
  86844. * @param position defines the position of the viewer
  86845. * @param xaxis defines the x axis of the viewer
  86846. * @param yaxis defines the y axis of the viewer
  86847. * @param zaxis defines the z axis of the viewer
  86848. */
  86849. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  86850. var scaleLines = this.scaleLines;
  86851. if (this._xmesh) {
  86852. this._xmesh.position.copyFrom(position);
  86853. }
  86854. if (this._ymesh) {
  86855. this._ymesh.position.copyFrom(position);
  86856. }
  86857. if (this._zmesh) {
  86858. this._zmesh.position.copyFrom(position);
  86859. }
  86860. var point2 = this._xline[1];
  86861. point2.x = xaxis.x * scaleLines;
  86862. point2.y = xaxis.y * scaleLines;
  86863. point2.z = xaxis.z * scaleLines;
  86864. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  86865. point2 = this._yline[1];
  86866. point2.x = yaxis.x * scaleLines;
  86867. point2.y = yaxis.y * scaleLines;
  86868. point2.z = yaxis.z * scaleLines;
  86869. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  86870. point2 = this._zline[1];
  86871. point2.x = zaxis.x * scaleLines;
  86872. point2.y = zaxis.y * scaleLines;
  86873. point2.z = zaxis.z * scaleLines;
  86874. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  86875. };
  86876. /** Releases resources */
  86877. AxesViewer.prototype.dispose = function () {
  86878. if (this._xmesh) {
  86879. this._xmesh.dispose();
  86880. }
  86881. if (this._ymesh) {
  86882. this._ymesh.dispose();
  86883. }
  86884. if (this._zmesh) {
  86885. this._zmesh.dispose();
  86886. }
  86887. this._xmesh = null;
  86888. this._ymesh = null;
  86889. this._zmesh = null;
  86890. this.scene = null;
  86891. };
  86892. return AxesViewer;
  86893. }());
  86894. Debug.AxesViewer = AxesViewer;
  86895. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86896. })(BABYLON || (BABYLON = {}));
  86897. //# sourceMappingURL=babylon.axesViewer.js.map
  86898. var BABYLON;
  86899. (function (BABYLON) {
  86900. var Debug;
  86901. (function (Debug) {
  86902. /**
  86903. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  86904. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  86905. */
  86906. var BoneAxesViewer = /** @class */ (function (_super) {
  86907. __extends(BoneAxesViewer, _super);
  86908. /**
  86909. * Creates a new BoneAxesViewer
  86910. * @param scene defines the hosting scene
  86911. * @param bone defines the target bone
  86912. * @param mesh defines the target mesh
  86913. * @param scaleLines defines a scaling factor for line length (1 by default)
  86914. */
  86915. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  86916. if (scaleLines === void 0) { scaleLines = 1; }
  86917. var _this = _super.call(this, scene, scaleLines) || this;
  86918. /** Gets current position */
  86919. _this.pos = BABYLON.Vector3.Zero();
  86920. /** Gets direction of X axis */
  86921. _this.xaxis = BABYLON.Vector3.Zero();
  86922. /** Gets direction of Y axis */
  86923. _this.yaxis = BABYLON.Vector3.Zero();
  86924. /** Gets direction of Z axis */
  86925. _this.zaxis = BABYLON.Vector3.Zero();
  86926. _this.mesh = mesh;
  86927. _this.bone = bone;
  86928. return _this;
  86929. }
  86930. /**
  86931. * Force the viewer to update
  86932. */
  86933. BoneAxesViewer.prototype.update = function () {
  86934. if (!this.mesh || !this.bone) {
  86935. return;
  86936. }
  86937. var bone = this.bone;
  86938. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  86939. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  86940. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  86941. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  86942. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  86943. };
  86944. /** Releases resources */
  86945. BoneAxesViewer.prototype.dispose = function () {
  86946. if (this.mesh) {
  86947. this.mesh = null;
  86948. this.bone = null;
  86949. _super.prototype.dispose.call(this);
  86950. }
  86951. };
  86952. return BoneAxesViewer;
  86953. }(Debug.AxesViewer));
  86954. Debug.BoneAxesViewer = BoneAxesViewer;
  86955. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86956. })(BABYLON || (BABYLON = {}));
  86957. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  86958. var BABYLON;
  86959. (function (BABYLON) {
  86960. var RayHelper = /** @class */ (function () {
  86961. function RayHelper(ray) {
  86962. this.ray = ray;
  86963. }
  86964. RayHelper.CreateAndShow = function (ray, scene, color) {
  86965. var helper = new RayHelper(ray);
  86966. helper.show(scene, color);
  86967. return helper;
  86968. };
  86969. RayHelper.prototype.show = function (scene, color) {
  86970. if (!this._renderFunction && this.ray) {
  86971. var ray = this.ray;
  86972. this._renderFunction = this._render.bind(this);
  86973. this._scene = scene;
  86974. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  86975. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  86976. if (this._renderFunction) {
  86977. this._scene.registerBeforeRender(this._renderFunction);
  86978. }
  86979. }
  86980. if (color && this._renderLine) {
  86981. this._renderLine.color.copyFrom(color);
  86982. }
  86983. };
  86984. RayHelper.prototype.hide = function () {
  86985. if (this._renderFunction && this._scene) {
  86986. this._scene.unregisterBeforeRender(this._renderFunction);
  86987. this._scene = null;
  86988. this._renderFunction = null;
  86989. if (this._renderLine) {
  86990. this._renderLine.dispose();
  86991. this._renderLine = null;
  86992. }
  86993. this._renderPoints = [];
  86994. }
  86995. };
  86996. RayHelper.prototype._render = function () {
  86997. var ray = this.ray;
  86998. if (!ray) {
  86999. return;
  87000. }
  87001. var point = this._renderPoints[1];
  87002. var len = Math.min(ray.length, 1000000);
  87003. point.copyFrom(ray.direction);
  87004. point.scaleInPlace(len);
  87005. point.addInPlace(ray.origin);
  87006. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  87007. };
  87008. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  87009. this._attachedToMesh = mesh;
  87010. var ray = this.ray;
  87011. if (!ray) {
  87012. return;
  87013. }
  87014. if (!ray.direction) {
  87015. ray.direction = BABYLON.Vector3.Zero();
  87016. }
  87017. if (!ray.origin) {
  87018. ray.origin = BABYLON.Vector3.Zero();
  87019. }
  87020. if (length) {
  87021. ray.length = length;
  87022. }
  87023. if (!meshSpaceOrigin) {
  87024. meshSpaceOrigin = BABYLON.Vector3.Zero();
  87025. }
  87026. if (!meshSpaceDirection) {
  87027. // -1 so that this will work with Mesh.lookAt
  87028. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  87029. }
  87030. if (!this._meshSpaceDirection) {
  87031. this._meshSpaceDirection = meshSpaceDirection.clone();
  87032. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  87033. }
  87034. else {
  87035. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  87036. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  87037. }
  87038. if (!this._updateToMeshFunction) {
  87039. this._updateToMeshFunction = this._updateToMesh.bind(this);
  87040. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  87041. }
  87042. this._updateToMesh();
  87043. };
  87044. RayHelper.prototype.detachFromMesh = function () {
  87045. if (this._attachedToMesh) {
  87046. if (this._updateToMeshFunction) {
  87047. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  87048. }
  87049. this._attachedToMesh = null;
  87050. this._updateToMeshFunction = null;
  87051. }
  87052. };
  87053. RayHelper.prototype._updateToMesh = function () {
  87054. var ray = this.ray;
  87055. if (!this._attachedToMesh || !ray) {
  87056. return;
  87057. }
  87058. if (this._attachedToMesh._isDisposed) {
  87059. this.detachFromMesh();
  87060. return;
  87061. }
  87062. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  87063. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  87064. };
  87065. RayHelper.prototype.dispose = function () {
  87066. this.hide();
  87067. this.detachFromMesh();
  87068. this.ray = null;
  87069. };
  87070. return RayHelper;
  87071. }());
  87072. BABYLON.RayHelper = RayHelper;
  87073. })(BABYLON || (BABYLON = {}));
  87074. //# sourceMappingURL=babylon.rayHelper.js.map
  87075. var BABYLON;
  87076. (function (BABYLON) {
  87077. // load the inspector using require, if not present in the global namespace.
  87078. var DebugLayer = /** @class */ (function () {
  87079. function DebugLayer(scene) {
  87080. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  87081. this._scene = scene;
  87082. // load inspector using require, if it doesn't exist on the global namespace.
  87083. }
  87084. /** Creates the inspector window. */
  87085. DebugLayer.prototype._createInspector = function (config) {
  87086. if (config === void 0) { config = {}; }
  87087. var popup = config.popup || false;
  87088. var initialTab = config.initialTab || 0;
  87089. var parentElement = config.parentElement || null;
  87090. if (!this._inspector) {
  87091. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  87092. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  87093. } // else nothing to do,; instance is already existing
  87094. };
  87095. DebugLayer.prototype.isVisible = function () {
  87096. if (!this._inspector) {
  87097. return false;
  87098. }
  87099. return true;
  87100. };
  87101. DebugLayer.prototype.hide = function () {
  87102. if (this._inspector) {
  87103. try {
  87104. this._inspector.dispose();
  87105. }
  87106. catch (e) {
  87107. // If the inspector has been removed directly from the inspector tool
  87108. }
  87109. this.onPropertyChangedObservable.clear();
  87110. this._inspector = null;
  87111. }
  87112. };
  87113. /**
  87114. *
  87115. * Launch the debugLayer.
  87116. *
  87117. * initialTab:
  87118. * | Value | Tab Name |
  87119. * | --- | --- |
  87120. * | 0 | Scene |
  87121. * | 1 | Console |
  87122. * | 2 | Stats |
  87123. * | 3 | Textures |
  87124. * | 4 | Mesh |
  87125. * | 5 | Light |
  87126. * | 6 | Material |
  87127. * | 7 | GLTF |
  87128. * | 8 | GUI |
  87129. * | 9 | Physics |
  87130. * | 10 | Camera |
  87131. * | 11 | Audio |
  87132. *
  87133. */
  87134. DebugLayer.prototype.show = function (config) {
  87135. if (config === void 0) { config = {}; }
  87136. if (typeof this.BJSINSPECTOR == 'undefined') {
  87137. // Load inspector and add it to the DOM
  87138. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  87139. }
  87140. else {
  87141. // Otherwise creates the inspector
  87142. this._createInspector(config);
  87143. this.onPropertyChangedObservable = new BABYLON.Observable();
  87144. }
  87145. };
  87146. /**
  87147. * Gets the active tab
  87148. * @return the index of the active tab or -1 if the inspector is hidden
  87149. */
  87150. DebugLayer.prototype.getActiveTab = function () {
  87151. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  87152. };
  87153. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  87154. return DebugLayer;
  87155. }());
  87156. BABYLON.DebugLayer = DebugLayer;
  87157. })(BABYLON || (BABYLON = {}));
  87158. //# sourceMappingURL=babylon.debugLayer.js.map
  87159. var BABYLON;
  87160. (function (BABYLON) {
  87161. var Debug;
  87162. (function (Debug) {
  87163. /**
  87164. * Used to show the physics impostor around the specific mesh
  87165. */
  87166. var PhysicsViewer = /** @class */ (function () {
  87167. /**
  87168. * Creates a new PhysicsViewer
  87169. * @param scene defines the hosting scene
  87170. */
  87171. function PhysicsViewer(scene) {
  87172. /** @hidden */
  87173. this._impostors = [];
  87174. /** @hidden */
  87175. this._meshes = [];
  87176. /** @hidden */
  87177. this._numMeshes = 0;
  87178. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  87179. var physicEngine = this._scene.getPhysicsEngine();
  87180. if (physicEngine) {
  87181. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  87182. }
  87183. }
  87184. /** @hidden */
  87185. PhysicsViewer.prototype._updateDebugMeshes = function () {
  87186. var plugin = this._physicsEnginePlugin;
  87187. for (var i = 0; i < this._numMeshes; i++) {
  87188. var impostor = this._impostors[i];
  87189. if (!impostor) {
  87190. continue;
  87191. }
  87192. if (impostor.isDisposed) {
  87193. this.hideImpostor(this._impostors[i--]);
  87194. }
  87195. else {
  87196. var mesh = this._meshes[i];
  87197. if (mesh && plugin) {
  87198. plugin.syncMeshWithImpostor(mesh, impostor);
  87199. }
  87200. }
  87201. }
  87202. };
  87203. /**
  87204. * Renders a specified physic impostor
  87205. * @param impostor defines the impostor to render
  87206. */
  87207. PhysicsViewer.prototype.showImpostor = function (impostor) {
  87208. if (!this._scene) {
  87209. return;
  87210. }
  87211. for (var i = 0; i < this._numMeshes; i++) {
  87212. if (this._impostors[i] == impostor) {
  87213. return;
  87214. }
  87215. }
  87216. var debugMesh = this._getDebugMesh(impostor, this._scene);
  87217. if (debugMesh) {
  87218. this._impostors[this._numMeshes] = impostor;
  87219. this._meshes[this._numMeshes] = debugMesh;
  87220. if (this._numMeshes === 0) {
  87221. this._renderFunction = this._updateDebugMeshes.bind(this);
  87222. this._scene.registerBeforeRender(this._renderFunction);
  87223. }
  87224. this._numMeshes++;
  87225. }
  87226. };
  87227. /**
  87228. * Hides a specified physic impostor
  87229. * @param impostor defines the impostor to hide
  87230. */
  87231. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  87232. if (!impostor || !this._scene) {
  87233. return;
  87234. }
  87235. var removed = false;
  87236. for (var i = 0; i < this._numMeshes; i++) {
  87237. if (this._impostors[i] == impostor) {
  87238. var mesh = this._meshes[i];
  87239. if (!mesh) {
  87240. continue;
  87241. }
  87242. this._scene.removeMesh(mesh);
  87243. mesh.dispose();
  87244. this._numMeshes--;
  87245. if (this._numMeshes > 0) {
  87246. this._meshes[i] = this._meshes[this._numMeshes];
  87247. this._impostors[i] = this._impostors[this._numMeshes];
  87248. this._meshes[this._numMeshes] = null;
  87249. this._impostors[this._numMeshes] = null;
  87250. }
  87251. else {
  87252. this._meshes[0] = null;
  87253. this._impostors[0] = null;
  87254. }
  87255. removed = true;
  87256. break;
  87257. }
  87258. }
  87259. if (removed && this._numMeshes === 0) {
  87260. this._scene.unregisterBeforeRender(this._renderFunction);
  87261. }
  87262. };
  87263. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  87264. if (!this._debugMaterial) {
  87265. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  87266. this._debugMaterial.wireframe = true;
  87267. }
  87268. return this._debugMaterial;
  87269. };
  87270. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  87271. if (!this._debugBoxMesh) {
  87272. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  87273. this._debugBoxMesh.renderingGroupId = 1;
  87274. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  87275. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  87276. scene.removeMesh(this._debugBoxMesh);
  87277. }
  87278. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  87279. };
  87280. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  87281. if (!this._debugSphereMesh) {
  87282. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  87283. this._debugSphereMesh.renderingGroupId = 1;
  87284. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  87285. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  87286. scene.removeMesh(this._debugSphereMesh);
  87287. }
  87288. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  87289. };
  87290. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  87291. var mesh = null;
  87292. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  87293. mesh = this._getDebugBoxMesh(scene);
  87294. impostor.getBoxSizeToRef(mesh.scaling);
  87295. }
  87296. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  87297. mesh = this._getDebugSphereMesh(scene);
  87298. var radius = impostor.getRadius();
  87299. mesh.scaling.x = radius * 2;
  87300. mesh.scaling.y = radius * 2;
  87301. mesh.scaling.z = radius * 2;
  87302. }
  87303. return mesh;
  87304. };
  87305. /** Releases all resources */
  87306. PhysicsViewer.prototype.dispose = function () {
  87307. for (var i = 0; i < this._numMeshes; i++) {
  87308. this.hideImpostor(this._impostors[i]);
  87309. }
  87310. if (this._debugBoxMesh) {
  87311. this._debugBoxMesh.dispose();
  87312. }
  87313. if (this._debugSphereMesh) {
  87314. this._debugSphereMesh.dispose();
  87315. }
  87316. if (this._debugMaterial) {
  87317. this._debugMaterial.dispose();
  87318. }
  87319. this._impostors.length = 0;
  87320. this._scene = null;
  87321. this._physicsEnginePlugin = null;
  87322. };
  87323. return PhysicsViewer;
  87324. }());
  87325. Debug.PhysicsViewer = PhysicsViewer;
  87326. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87327. })(BABYLON || (BABYLON = {}));
  87328. //# sourceMappingURL=babylon.physicsViewer.js.map
  87329. var BABYLON;
  87330. (function (BABYLON) {
  87331. var BoundingBoxRenderer = /** @class */ (function () {
  87332. function BoundingBoxRenderer(scene) {
  87333. this.frontColor = new BABYLON.Color3(1, 1, 1);
  87334. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  87335. this.showBackLines = true;
  87336. this.renderList = new BABYLON.SmartArray(32);
  87337. this._vertexBuffers = {};
  87338. this._scene = scene;
  87339. }
  87340. BoundingBoxRenderer.prototype._prepareRessources = function () {
  87341. if (this._colorShader) {
  87342. return;
  87343. }
  87344. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  87345. attributes: [BABYLON.VertexBuffer.PositionKind],
  87346. uniforms: ["world", "viewProjection", "color"]
  87347. });
  87348. var engine = this._scene.getEngine();
  87349. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  87350. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  87351. this._createIndexBuffer();
  87352. };
  87353. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  87354. var engine = this._scene.getEngine();
  87355. 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]);
  87356. };
  87357. BoundingBoxRenderer.prototype._rebuild = function () {
  87358. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87359. if (vb) {
  87360. vb._rebuild();
  87361. }
  87362. this._createIndexBuffer();
  87363. };
  87364. BoundingBoxRenderer.prototype.reset = function () {
  87365. this.renderList.reset();
  87366. };
  87367. BoundingBoxRenderer.prototype.render = function () {
  87368. if (this.renderList.length === 0) {
  87369. return;
  87370. }
  87371. this._prepareRessources();
  87372. if (!this._colorShader.isReady()) {
  87373. return;
  87374. }
  87375. var engine = this._scene.getEngine();
  87376. engine.setDepthWrite(false);
  87377. this._colorShader._preBind();
  87378. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  87379. var boundingBox = this.renderList.data[boundingBoxIndex];
  87380. var min = boundingBox.minimum;
  87381. var max = boundingBox.maximum;
  87382. var diff = max.subtract(min);
  87383. var median = min.add(diff.scale(0.5));
  87384. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  87385. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  87386. .multiply(boundingBox.getWorldMatrix());
  87387. // VBOs
  87388. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  87389. if (this.showBackLines) {
  87390. // Back
  87391. engine.setDepthFunctionToGreaterOrEqual();
  87392. this._scene.resetCachedMaterial();
  87393. this._colorShader.setColor4("color", this.backColor.toColor4());
  87394. this._colorShader.bind(worldMatrix);
  87395. // Draw order
  87396. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87397. }
  87398. // Front
  87399. engine.setDepthFunctionToLess();
  87400. this._scene.resetCachedMaterial();
  87401. this._colorShader.setColor4("color", this.frontColor.toColor4());
  87402. this._colorShader.bind(worldMatrix);
  87403. // Draw order
  87404. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87405. }
  87406. this._colorShader.unbind();
  87407. engine.setDepthFunctionToLessOrEqual();
  87408. engine.setDepthWrite(true);
  87409. };
  87410. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  87411. this._prepareRessources();
  87412. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  87413. return;
  87414. }
  87415. var engine = this._scene.getEngine();
  87416. engine.setDepthWrite(false);
  87417. engine.setColorWrite(false);
  87418. this._colorShader._preBind();
  87419. var boundingBox = mesh._boundingInfo.boundingBox;
  87420. var min = boundingBox.minimum;
  87421. var max = boundingBox.maximum;
  87422. var diff = max.subtract(min);
  87423. var median = min.add(diff.scale(0.5));
  87424. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  87425. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  87426. .multiply(boundingBox.getWorldMatrix());
  87427. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  87428. engine.setDepthFunctionToLess();
  87429. this._scene.resetCachedMaterial();
  87430. this._colorShader.bind(worldMatrix);
  87431. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87432. this._colorShader.unbind();
  87433. engine.setDepthFunctionToLessOrEqual();
  87434. engine.setDepthWrite(true);
  87435. engine.setColorWrite(true);
  87436. };
  87437. BoundingBoxRenderer.prototype.dispose = function () {
  87438. if (!this._colorShader) {
  87439. return;
  87440. }
  87441. this.renderList.dispose();
  87442. this._colorShader.dispose();
  87443. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87444. if (buffer) {
  87445. buffer.dispose();
  87446. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  87447. }
  87448. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  87449. };
  87450. return BoundingBoxRenderer;
  87451. }());
  87452. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  87453. })(BABYLON || (BABYLON = {}));
  87454. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  87455. var BABYLON;
  87456. (function (BABYLON) {
  87457. /**
  87458. * Renders a layer on top of an existing scene
  87459. */
  87460. var UtilityLayerRenderer = /** @class */ (function () {
  87461. /**
  87462. * Instantiates a UtilityLayerRenderer
  87463. * @param originalScene the original scene that will be rendered on top of
  87464. */
  87465. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  87466. var _this = this;
  87467. this.originalScene = originalScene;
  87468. this._pointerCaptures = {};
  87469. this._lastPointerEvents = {};
  87470. /**
  87471. * If the utility layer should automatically be rendered on top of existing scene
  87472. */
  87473. this.shouldRender = true;
  87474. /**
  87475. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  87476. */
  87477. this.onlyCheckPointerDownEvents = true;
  87478. /**
  87479. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  87480. */
  87481. this.processAllEvents = false;
  87482. /**
  87483. * Observable raised when the pointer move from the utility layer scene to the main scene
  87484. */
  87485. this.onPointerOutObservable = new BABYLON.Observable();
  87486. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  87487. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  87488. originalScene.getEngine().scenes.pop();
  87489. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  87490. this.utilityLayerScene.detachControl();
  87491. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  87492. if (!_this.processAllEvents) {
  87493. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  87494. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  87495. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  87496. return;
  87497. }
  87498. }
  87499. var pointerEvent = (prePointerInfo.event);
  87500. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  87501. return;
  87502. }
  87503. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  87504. if (!prePointerInfo.ray && utilityScenePick) {
  87505. prePointerInfo.ray = utilityScenePick.ray;
  87506. }
  87507. // always fire the prepointer oversvable
  87508. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  87509. // allow every non pointer down event to flow to the utility layer
  87510. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  87511. if (!prePointerInfo.skipOnPointerObservable) {
  87512. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87513. }
  87514. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  87515. _this._pointerCaptures[pointerEvent.pointerId] = false;
  87516. }
  87517. return;
  87518. }
  87519. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  87520. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  87521. if (utilityScenePick && utilityScenePick.hit) {
  87522. if (!prePointerInfo.skipOnPointerObservable) {
  87523. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87524. }
  87525. prePointerInfo.skipOnPointerObservable = true;
  87526. }
  87527. }
  87528. else {
  87529. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  87530. var pointerEvent_1 = (prePointerInfo.event);
  87531. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  87532. if (originalScenePick && utilityScenePick) {
  87533. // No pick in utility scene
  87534. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  87535. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  87536. // We touched an utility mesh present in the main scene
  87537. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  87538. prePointerInfo.skipOnPointerObservable = true;
  87539. }
  87540. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87541. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  87542. }
  87543. }
  87544. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  87545. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  87546. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  87547. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  87548. }
  87549. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  87550. // We have a pick in both scenes but main is closer than utility
  87551. // We touched an utility mesh present in the main scene
  87552. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  87553. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  87554. prePointerInfo.skipOnPointerObservable = true;
  87555. }
  87556. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  87557. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  87558. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  87559. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  87560. }
  87561. }
  87562. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  87563. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  87564. }
  87565. }
  87566. }
  87567. });
  87568. // Render directly on top of existing scene without clearing
  87569. this.utilityLayerScene.autoClear = false;
  87570. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  87571. if (_this.shouldRender) {
  87572. _this.render();
  87573. }
  87574. });
  87575. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  87576. _this.dispose();
  87577. });
  87578. this._updateCamera();
  87579. }
  87580. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  87581. if (!prePointerInfo.skipOnPointerObservable) {
  87582. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  87583. this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  87584. }
  87585. };
  87586. /**
  87587. * Renders the utility layers scene on top of the original scene
  87588. */
  87589. UtilityLayerRenderer.prototype.render = function () {
  87590. this._updateCamera();
  87591. this.utilityLayerScene.render(false);
  87592. };
  87593. /**
  87594. * Disposes of the renderer
  87595. */
  87596. UtilityLayerRenderer.prototype.dispose = function () {
  87597. this.onPointerOutObservable.clear();
  87598. if (this._afterRenderObserver) {
  87599. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  87600. }
  87601. if (this._sceneDisposeObserver) {
  87602. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  87603. }
  87604. if (this._originalPointerObserver) {
  87605. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  87606. }
  87607. this.utilityLayerScene.dispose();
  87608. };
  87609. UtilityLayerRenderer.prototype._updateCamera = function () {
  87610. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  87611. };
  87612. return UtilityLayerRenderer;
  87613. }());
  87614. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  87615. })(BABYLON || (BABYLON = {}));
  87616. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  87617. //# sourceMappingURL=babylon.behavior.js.map
  87618. var BABYLON;
  87619. (function (BABYLON) {
  87620. /**
  87621. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  87622. */
  87623. var PointerDragBehavior = /** @class */ (function () {
  87624. /**
  87625. * Creates a pointer drag behavior that can be attached to a mesh
  87626. * @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)
  87627. */
  87628. function PointerDragBehavior(options) {
  87629. this.options = options;
  87630. /**
  87631. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  87632. */
  87633. this.currentDraggingPointerID = -1;
  87634. /**
  87635. * If the behavior is currently in a dragging state
  87636. */
  87637. this.dragging = false;
  87638. /**
  87639. * 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)
  87640. */
  87641. this.dragDeltaRatio = 0.2;
  87642. // Debug mode will display drag planes to help visualize behavior
  87643. this._debugMode = false;
  87644. this._moving = false;
  87645. /**
  87646. * Fires each time the attached mesh is dragged with the pointer
  87647. * * delta between last drag position and current drag position in world space
  87648. * * dragDistance along the drag axis
  87649. * * dragPlaneNormal normal of the current drag plane used during the drag
  87650. * * dragPlanePoint in world space where the drag intersects the drag plane
  87651. */
  87652. this.onDragObservable = new BABYLON.Observable();
  87653. /**
  87654. * Fires each time a drag begins (eg. mouse down on mesh)
  87655. */
  87656. this.onDragStartObservable = new BABYLON.Observable();
  87657. /**
  87658. * Fires each time a drag ends (eg. mouse release after drag)
  87659. */
  87660. this.onDragEndObservable = new BABYLON.Observable();
  87661. /**
  87662. * If the attached mesh should be moved when dragged
  87663. */
  87664. this.moveAttached = true;
  87665. /**
  87666. * If the drag behavior will react to drag events (Default: true)
  87667. */
  87668. this.enabled = true;
  87669. /**
  87670. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  87671. */
  87672. this.useObjectOrienationForDragging = true;
  87673. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  87674. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  87675. // Variables to avoid instantiation in the below method
  87676. this._pointA = new BABYLON.Vector3(0, 0, 0);
  87677. this._pointB = new BABYLON.Vector3(0, 0, 0);
  87678. this._pointC = new BABYLON.Vector3(0, 0, 0);
  87679. this._lineA = new BABYLON.Vector3(0, 0, 0);
  87680. this._lineB = new BABYLON.Vector3(0, 0, 0);
  87681. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  87682. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  87683. var optionCount = 0;
  87684. if (options === undefined) {
  87685. options = {};
  87686. }
  87687. if (options.dragAxis) {
  87688. optionCount++;
  87689. }
  87690. if (options.dragPlaneNormal) {
  87691. optionCount++;
  87692. }
  87693. if (optionCount > 1) {
  87694. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  87695. }
  87696. }
  87697. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  87698. /**
  87699. * The name of the behavior
  87700. */
  87701. get: function () {
  87702. return "PointerDrag";
  87703. },
  87704. enumerable: true,
  87705. configurable: true
  87706. });
  87707. /**
  87708. * Initializes the behavior
  87709. */
  87710. PointerDragBehavior.prototype.init = function () { };
  87711. /**
  87712. * Attaches the drag behavior the passed in mesh
  87713. * @param ownerNode The mesh that will be dragged around once attached
  87714. */
  87715. PointerDragBehavior.prototype.attach = function (ownerNode) {
  87716. var _this = this;
  87717. this._scene = ownerNode.getScene();
  87718. this._attachedNode = ownerNode;
  87719. // Initialize drag plane to not interfere with existing scene
  87720. if (!PointerDragBehavior._planeScene) {
  87721. if (this._debugMode) {
  87722. PointerDragBehavior._planeScene = this._scene;
  87723. }
  87724. else {
  87725. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  87726. this._scene.getEngine().scenes.pop();
  87727. }
  87728. }
  87729. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  87730. // State of the drag
  87731. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  87732. var delta = new BABYLON.Vector3(0, 0, 0);
  87733. var dragLength = 0;
  87734. var targetPosition = new BABYLON.Vector3(0, 0, 0);
  87735. var pickPredicate = function (m) {
  87736. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  87737. };
  87738. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  87739. if (!_this.enabled) {
  87740. return;
  87741. }
  87742. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  87743. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  87744. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  87745. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  87746. if (pickedPoint) {
  87747. _this.dragging = true;
  87748. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  87749. _this.lastDragPosition.copyFrom(pickedPoint);
  87750. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });
  87751. targetPosition.copyFrom(_this._attachedNode.absolutePosition);
  87752. }
  87753. }
  87754. }
  87755. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  87756. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  87757. _this.releaseDrag();
  87758. }
  87759. }
  87760. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  87761. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  87762. _this._moving = true;
  87763. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  87764. if (pickedPoint) {
  87765. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  87766. // depending on the drag mode option drag accordingly
  87767. if (_this.options.dragAxis) {
  87768. // Convert local drag axis to world
  87769. BABYLON.Vector3.TransformCoordinatesToRef(_this.options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);
  87770. // Project delta drag from the drag plane onto the drag axis
  87771. pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);
  87772. dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);
  87773. _this._worldDragAxis.scaleToRef(dragLength, delta);
  87774. }
  87775. else {
  87776. dragLength = delta.length();
  87777. pickedPoint.subtractToRef(_this.lastDragPosition, delta);
  87778. }
  87779. targetPosition.addInPlace(delta);
  87780. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });
  87781. _this.lastDragPosition.copyFrom(pickedPoint);
  87782. }
  87783. }
  87784. }
  87785. });
  87786. this._scene.onBeforeRenderObservable.add(function () {
  87787. if (_this._moving && _this.moveAttached) {
  87788. // Slowly move mesh to avoid jitter
  87789. targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  87790. _this._tmpVector.scaleInPlace(0.2);
  87791. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  87792. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  87793. }
  87794. });
  87795. };
  87796. PointerDragBehavior.prototype.releaseDrag = function () {
  87797. this.dragging = false;
  87798. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  87799. this.currentDraggingPointerID = -1;
  87800. this._moving = false;
  87801. };
  87802. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  87803. var _this = this;
  87804. if (!ray) {
  87805. return null;
  87806. }
  87807. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  87808. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  87809. return pickResult.pickedPoint;
  87810. }
  87811. else {
  87812. return null;
  87813. }
  87814. };
  87815. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  87816. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  87817. this._pointA.copyFrom(dragPlanePosition);
  87818. if (this.options.dragAxis) {
  87819. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragAxis);
  87820. // Calculate plane normal in direction of camera but perpendicular to drag axis
  87821. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  87822. ray.origin.subtractToRef(this._pointA, this._pointC);
  87823. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  87824. // Get perpendicular line from direction to camera and drag axis
  87825. this._pointB.subtractToRef(this._pointA, this._lineA);
  87826. this._pointC.subtractToRef(this._pointA, this._lineB);
  87827. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  87828. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  87829. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  87830. this._lookAt.normalize();
  87831. this._dragPlane.position.copyFrom(this._pointA);
  87832. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  87833. this._dragPlane.lookAt(this._lookAt);
  87834. }
  87835. else if (this.options.dragPlaneNormal) {
  87836. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragPlaneNormal);
  87837. this._dragPlane.position.copyFrom(this._pointA);
  87838. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  87839. this._dragPlane.lookAt(this._lookAt);
  87840. }
  87841. else {
  87842. this._dragPlane.position.copyFrom(this._pointA);
  87843. this._dragPlane.lookAt(ray.origin);
  87844. }
  87845. this._dragPlane.computeWorldMatrix(true);
  87846. };
  87847. /**
  87848. * Detaches the behavior from the mesh
  87849. */
  87850. PointerDragBehavior.prototype.detach = function () {
  87851. if (this._pointerObserver) {
  87852. this._scene.onPointerObservable.remove(this._pointerObserver);
  87853. }
  87854. };
  87855. return PointerDragBehavior;
  87856. }());
  87857. BABYLON.PointerDragBehavior = PointerDragBehavior;
  87858. })(BABYLON || (BABYLON = {}));
  87859. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  87860. var BABYLON;
  87861. (function (BABYLON) {
  87862. /**
  87863. * A behavior that when attached to a mesh will allow the mesh to be scaled
  87864. */
  87865. var MultiPointerScaleBehavior = /** @class */ (function () {
  87866. function MultiPointerScaleBehavior() {
  87867. this._startDistance = 0;
  87868. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  87869. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  87870. this._sceneRenderObserver = null;
  87871. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  87872. this._dragBehaviorA.moveAttached = false;
  87873. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  87874. this._dragBehaviorB.moveAttached = false;
  87875. }
  87876. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  87877. /**
  87878. * The name of the behavior
  87879. */
  87880. get: function () {
  87881. return "MultiPointerScale";
  87882. },
  87883. enumerable: true,
  87884. configurable: true
  87885. });
  87886. /**
  87887. * Initializes the behavior
  87888. */
  87889. MultiPointerScaleBehavior.prototype.init = function () { };
  87890. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  87891. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  87892. };
  87893. /**
  87894. * Attaches the scale behavior the passed in mesh
  87895. * @param ownerNode The mesh that will be scaled around once attached
  87896. */
  87897. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  87898. var _this = this;
  87899. this._ownerNode = ownerNode;
  87900. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  87901. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  87902. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  87903. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  87904. _this._dragBehaviorA.releaseDrag();
  87905. }
  87906. else {
  87907. _this._initialScale.copyFrom(ownerNode.scaling);
  87908. _this._startDistance = _this._getCurrentDistance();
  87909. }
  87910. }
  87911. });
  87912. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  87913. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  87914. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  87915. _this._dragBehaviorB.releaseDrag();
  87916. }
  87917. else {
  87918. _this._initialScale.copyFrom(ownerNode.scaling);
  87919. _this._startDistance = _this._getCurrentDistance();
  87920. }
  87921. }
  87922. });
  87923. // Once both drag behaviors are active scale based on the distance between the two pointers
  87924. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  87925. behavior.onDragObservable.add(function () {
  87926. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  87927. var ratio = _this._getCurrentDistance() / _this._startDistance;
  87928. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  87929. }
  87930. });
  87931. });
  87932. ownerNode.addBehavior(this._dragBehaviorA);
  87933. ownerNode.addBehavior(this._dragBehaviorB);
  87934. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  87935. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  87936. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  87937. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  87938. if (change.length() > 0.01) {
  87939. ownerNode.scaling.addInPlace(change);
  87940. }
  87941. }
  87942. });
  87943. };
  87944. /**
  87945. * Detaches the behavior from the mesh
  87946. */
  87947. MultiPointerScaleBehavior.prototype.detach = function () {
  87948. var _this = this;
  87949. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  87950. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  87951. behavior.onDragStartObservable.clear();
  87952. behavior.onDragObservable.clear();
  87953. _this._ownerNode.removeBehavior(behavior);
  87954. });
  87955. };
  87956. return MultiPointerScaleBehavior;
  87957. }());
  87958. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  87959. })(BABYLON || (BABYLON = {}));
  87960. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  87961. var BABYLON;
  87962. (function (BABYLON) {
  87963. /**
  87964. * 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
  87965. */
  87966. var SixDofDragBehavior = /** @class */ (function () {
  87967. function SixDofDragBehavior() {
  87968. this._sceneRenderObserver = null;
  87969. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  87970. /**
  87971. * How much faster the object should move when the controller is moving towards it. This is useful to bring objects that are far away from the user to them faster. Set this to 0 to avoid any speed increase. (Default: 5)
  87972. */
  87973. this.zDragFactor = 5;
  87974. /**
  87975. * If the behavior is currently in a dragging state
  87976. */
  87977. this.dragging = false;
  87978. /**
  87979. * 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)
  87980. */
  87981. this.dragDeltaRatio = 0.2;
  87982. /**
  87983. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  87984. */
  87985. this.currentDraggingPointerID = -1;
  87986. }
  87987. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  87988. /**
  87989. * The name of the behavior
  87990. */
  87991. get: function () {
  87992. return "SixDofDrag";
  87993. },
  87994. enumerable: true,
  87995. configurable: true
  87996. });
  87997. /**
  87998. * Initializes the behavior
  87999. */
  88000. SixDofDragBehavior.prototype.init = function () { };
  88001. /**
  88002. * Attaches the scale behavior the passed in mesh
  88003. * @param ownerNode The mesh that will be scaled around once attached
  88004. */
  88005. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  88006. var _this = this;
  88007. this._ownerNode = ownerNode;
  88008. this._scene = this._ownerNode.getScene();
  88009. if (!SixDofDragBehavior._virtualScene) {
  88010. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  88011. this._scene.getEngine().scenes.pop();
  88012. }
  88013. var pickedMesh = null;
  88014. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  88015. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  88016. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  88017. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  88018. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  88019. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  88020. var pickPredicate = function (m) {
  88021. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  88022. };
  88023. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  88024. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  88025. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  88026. pickedMesh = pointerInfo.pickInfo.pickedMesh;
  88027. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  88028. // Set position and orientation of the controller
  88029. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  88030. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  88031. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  88032. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88033. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  88034. if (!pickedMesh.rotationQuaternion) {
  88035. pickedMesh.rotationQuaternion = new BABYLON.Quaternion();
  88036. }
  88037. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  88038. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  88039. // Update state
  88040. _this.dragging = true;
  88041. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  88042. }
  88043. }
  88044. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  88045. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  88046. _this.dragging = false;
  88047. _this.currentDraggingPointerID = -1;
  88048. pickedMesh = null;
  88049. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88050. }
  88051. }
  88052. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  88053. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  88054. // Calculate controller drag distance in controller space
  88055. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  88056. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  88057. var localOriginDragDifference = BABYLON.Vector3.TransformCoordinates(originDragDifference, BABYLON.Matrix.Invert(_this._virtualOriginMesh.getWorldMatrix().getRotationMatrix()));
  88058. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  88059. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  88060. var zDragDistance = BABYLON.Vector3.Dot(localOriginDragDifference, _this._virtualOriginMesh.position.normalizeToNew());
  88061. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? zDragDistance * _this.zDragFactor : zDragDistance * _this.zDragFactor * _this._virtualDragMesh.position.z;
  88062. if (_this._virtualDragMesh.position.z < 0) {
  88063. _this._virtualDragMesh.position.z = 0;
  88064. }
  88065. // Update the controller position
  88066. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  88067. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  88068. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88069. // Move the virtualObjectsPosition into the picked mesh's space if needed
  88070. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  88071. if (pickedMesh.parent) {
  88072. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  88073. }
  88074. }
  88075. }
  88076. });
  88077. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  88078. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  88079. if (_this.dragging && pickedMesh) {
  88080. // Slowly move mesh to avoid jitter
  88081. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  88082. }
  88083. });
  88084. };
  88085. /**
  88086. * Detaches the behavior from the mesh
  88087. */
  88088. SixDofDragBehavior.prototype.detach = function () {
  88089. this._scene.onPointerObservable.remove(this._pointerObserver);
  88090. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  88091. this._virtualOriginMesh.dispose();
  88092. this._virtualDragMesh.dispose();
  88093. };
  88094. return SixDofDragBehavior;
  88095. }());
  88096. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  88097. })(BABYLON || (BABYLON = {}));
  88098. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  88099. var BABYLON;
  88100. (function (BABYLON) {
  88101. /**
  88102. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  88103. */
  88104. var Gizmo = /** @class */ (function () {
  88105. /**
  88106. * Creates a gizmo
  88107. * @param gizmoLayer The utility layer the gizmo will be added to
  88108. */
  88109. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  88110. var _this = this;
  88111. this.gizmoLayer = gizmoLayer;
  88112. /**
  88113. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  88114. */
  88115. this.updateGizmoRotationToMatchAttachedMesh = true;
  88116. /**
  88117. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  88118. */
  88119. this.updateGizmoPositionToMatchAttachedMesh = true;
  88120. /**
  88121. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  88122. */
  88123. this._updateScale = true;
  88124. this._interactionsEnabled = true;
  88125. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  88126. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  88127. if (_this._updateScale && _this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  88128. var dist = _this.attachedMesh.position.subtract(_this.gizmoLayer.utilityLayerScene.activeCamera.position).length() / 3;
  88129. _this._rootMesh.scaling.set(dist, dist, dist);
  88130. }
  88131. if (_this.attachedMesh) {
  88132. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  88133. if (!_this._rootMesh.rotationQuaternion) {
  88134. _this._rootMesh.rotationQuaternion = new BABYLON.Quaternion();
  88135. }
  88136. BABYLON.Quaternion.FromRotationMatrixToRef(_this.attachedMesh.getWorldMatrix().getRotationMatrix(), _this._rootMesh.rotationQuaternion);
  88137. }
  88138. if (_this.updateGizmoPositionToMatchAttachedMesh) {
  88139. _this._rootMesh.position.copyFrom(_this.attachedMesh.absolutePosition);
  88140. }
  88141. }
  88142. });
  88143. }
  88144. Gizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88145. };
  88146. Object.defineProperty(Gizmo.prototype, "interactionsEnabled", {
  88147. get: function () {
  88148. return this._interactionsEnabled;
  88149. },
  88150. /**
  88151. * If interactions are enabled with this gizmo. (eg. dragging/rotation)
  88152. */
  88153. set: function (value) {
  88154. this._interactionsEnabled = value;
  88155. this._onInteractionsEnabledChanged(value);
  88156. },
  88157. enumerable: true,
  88158. configurable: true
  88159. });
  88160. /**
  88161. * Disposes of the gizmo
  88162. */
  88163. Gizmo.prototype.dispose = function () {
  88164. this._rootMesh.dispose();
  88165. if (this._beforeRenderObserver) {
  88166. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  88167. }
  88168. };
  88169. return Gizmo;
  88170. }());
  88171. BABYLON.Gizmo = Gizmo;
  88172. })(BABYLON || (BABYLON = {}));
  88173. //# sourceMappingURL=babylon.gizmo.js.map
  88174. var BABYLON;
  88175. (function (BABYLON) {
  88176. /**
  88177. * Single axis drag gizmo
  88178. */
  88179. var AxisDragGizmo = /** @class */ (function (_super) {
  88180. __extends(AxisDragGizmo, _super);
  88181. /**
  88182. * Creates an AxisDragGizmo
  88183. * @param gizmoLayer The utility layer the gizmo will be added to
  88184. * @param dragAxis The axis which the gizmo will be able to drag on
  88185. * @param color The color of the gizmo
  88186. */
  88187. function AxisDragGizmo(gizmoLayer, dragAxis, color) {
  88188. var _this = _super.call(this, gizmoLayer) || this;
  88189. _this.updateGizmoRotationToMatchAttachedMesh = false;
  88190. // Create Material
  88191. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88192. coloredMaterial.disableLighting = true;
  88193. coloredMaterial.emissiveColor = color;
  88194. // Build mesh on root node
  88195. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  88196. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  88197. _this._rootMesh.addChild(arrowMesh);
  88198. _this._rootMesh.addChild(arrowTail);
  88199. // Position arrow pointing in its drag axis
  88200. arrowMesh.scaling.scaleInPlace(0.1);
  88201. arrowMesh.material = coloredMaterial;
  88202. arrowMesh.rotation.x = Math.PI / 2;
  88203. arrowMesh.position.z += 0.3;
  88204. arrowTail.rotation.x = Math.PI / 2;
  88205. arrowTail.material = coloredMaterial;
  88206. arrowTail.position.z += 0.2;
  88207. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  88208. // Add drag behavior to handle events when the gizmo is dragged
  88209. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: new BABYLON.Vector3(0, 0, 1) });
  88210. _this._dragBehavior.moveAttached = false;
  88211. _this._rootMesh.addBehavior(_this._dragBehavior);
  88212. _this._dragBehavior.onDragObservable.add(function (event) {
  88213. if (!_this.interactionsEnabled) {
  88214. return;
  88215. }
  88216. if (_this.attachedMesh) {
  88217. _this.attachedMesh.position.addInPlace(event.delta);
  88218. }
  88219. });
  88220. return _this;
  88221. }
  88222. AxisDragGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88223. this._dragBehavior.enabled = value;
  88224. };
  88225. /**
  88226. * Disposes of the gizmo
  88227. */
  88228. AxisDragGizmo.prototype.dispose = function () {
  88229. this._dragBehavior.detach();
  88230. _super.prototype.dispose.call(this);
  88231. };
  88232. return AxisDragGizmo;
  88233. }(BABYLON.Gizmo));
  88234. BABYLON.AxisDragGizmo = AxisDragGizmo;
  88235. })(BABYLON || (BABYLON = {}));
  88236. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  88237. var BABYLON;
  88238. (function (BABYLON) {
  88239. /**
  88240. * Single axis scale gizmo
  88241. */
  88242. var AxisScaleGizmo = /** @class */ (function (_super) {
  88243. __extends(AxisScaleGizmo, _super);
  88244. /**
  88245. * Creates an AxisScaleGizmo
  88246. * @param gizmoLayer The utility layer the gizmo will be added to
  88247. * @param dragAxis The axis which the gizmo will be able to scale on
  88248. * @param color The color of the gizmo
  88249. */
  88250. function AxisScaleGizmo(gizmoLayer, dragAxis, color) {
  88251. var _this = _super.call(this, gizmoLayer) || this;
  88252. _this.updateGizmoRotationToMatchAttachedMesh = false;
  88253. // Create Material
  88254. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88255. coloredMaterial.disableLighting = true;
  88256. coloredMaterial.emissiveColor = color;
  88257. // Build mesh on root node
  88258. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 1 }, gizmoLayer.utilityLayerScene);
  88259. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  88260. _this._rootMesh.addChild(arrowMesh);
  88261. _this._rootMesh.addChild(arrowTail);
  88262. // Position arrow pointing in its drag axis
  88263. arrowMesh.scaling.scaleInPlace(0.1);
  88264. arrowMesh.material = coloredMaterial;
  88265. arrowMesh.rotation.x = Math.PI / 2;
  88266. arrowMesh.position.z += 0.3;
  88267. arrowTail.rotation.x = Math.PI / 2;
  88268. arrowTail.material = coloredMaterial;
  88269. arrowTail.position.z += 0.2;
  88270. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  88271. // Add drag behavior to handle events when the gizmo is dragged
  88272. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: new BABYLON.Vector3(0, 0, 1) });
  88273. _this._dragBehavior.moveAttached = false;
  88274. _this._rootMesh.addBehavior(_this._dragBehavior);
  88275. _this._dragBehavior.onDragObservable.add(function (event) {
  88276. if (!_this.interactionsEnabled) {
  88277. return;
  88278. }
  88279. if (_this.attachedMesh) {
  88280. _this.attachedMesh.scaling.addInPlace(event.delta);
  88281. }
  88282. });
  88283. return _this;
  88284. }
  88285. AxisScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88286. this._dragBehavior.enabled = value;
  88287. };
  88288. /**
  88289. * Disposes of the gizmo
  88290. */
  88291. AxisScaleGizmo.prototype.dispose = function () {
  88292. this._dragBehavior.detach();
  88293. _super.prototype.dispose.call(this);
  88294. };
  88295. return AxisScaleGizmo;
  88296. }(BABYLON.Gizmo));
  88297. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  88298. })(BABYLON || (BABYLON = {}));
  88299. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  88300. var BABYLON;
  88301. (function (BABYLON) {
  88302. /**
  88303. * Single plane rotation gizmo
  88304. */
  88305. var PlaneRotationGizmo = /** @class */ (function (_super) {
  88306. __extends(PlaneRotationGizmo, _super);
  88307. /**
  88308. * Creates a PlaneRotationGizmo
  88309. * @param gizmoLayer The utility layer the gizmo will be added to
  88310. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  88311. * @param color The color of the gizmo
  88312. */
  88313. function PlaneRotationGizmo(gizmoLayer, planeNormal, color) {
  88314. var _this = _super.call(this, gizmoLayer) || this;
  88315. _this.updateGizmoRotationToMatchAttachedMesh = false;
  88316. // Create Material
  88317. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88318. coloredMaterial.disableLighting = true;
  88319. coloredMaterial.emissiveColor = color;
  88320. // Build mesh on root node
  88321. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.3, 20, gizmoLayer.utilityLayerScene, false);
  88322. _this._rootMesh.addChild(rotationMesh);
  88323. // Position arrow pointing in its drag axis
  88324. rotationMesh.scaling.scaleInPlace(0.1);
  88325. rotationMesh.material = coloredMaterial;
  88326. rotationMesh.rotation.x = Math.PI / 2;
  88327. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  88328. // Add drag behavior to handle events when the gizmo is dragged
  88329. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: new BABYLON.Vector3(0, 0, 1) });
  88330. _this._dragBehavior.moveAttached = false;
  88331. _this._rootMesh.addBehavior(_this._dragBehavior);
  88332. var lastDragPosition = null;
  88333. _this._dragBehavior.onDragStartObservable.add(function (e) {
  88334. if (!_this.interactionsEnabled) {
  88335. return;
  88336. }
  88337. lastDragPosition = e.dragPlanePoint;
  88338. });
  88339. _this._dragBehavior.onDragObservable.add(function (event) {
  88340. if (!_this.interactionsEnabled) {
  88341. return;
  88342. }
  88343. if (_this.attachedMesh && lastDragPosition) {
  88344. if (!_this.attachedMesh.rotationQuaternion) {
  88345. _this.attachedMesh.rotationQuaternion = new BABYLON.Quaternion();
  88346. }
  88347. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  88348. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  88349. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  88350. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  88351. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  88352. var angle = Math.atan2(cross.length(), dot);
  88353. var up = planeNormal.clone();
  88354. // Flip up vector depending on which side the camera is on
  88355. if (gizmoLayer.utilityLayerScene.activeCamera) {
  88356. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  88357. if (BABYLON.Vector3.Dot(camVec, up) > 0) {
  88358. up.scaleInPlace(-1);
  88359. }
  88360. }
  88361. var halfCircleSide = BABYLON.Vector3.Dot(up, cross) > 0.0;
  88362. if (halfCircleSide)
  88363. angle = -angle;
  88364. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  88365. var quaternionCoefficient = Math.sin(angle / 2);
  88366. var amountToRotate = new BABYLON.Quaternion(up.x * quaternionCoefficient, up.y * quaternionCoefficient, up.z * quaternionCoefficient, Math.cos(angle / 2));
  88367. // Rotate selected mesh quaternion over fixed axis
  88368. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  88369. lastDragPosition = event.dragPlanePoint;
  88370. }
  88371. });
  88372. return _this;
  88373. }
  88374. PlaneRotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88375. this._dragBehavior.enabled = value;
  88376. };
  88377. /**
  88378. * Disposes of the gizmo
  88379. */
  88380. PlaneRotationGizmo.prototype.dispose = function () {
  88381. this._dragBehavior.detach();
  88382. _super.prototype.dispose.call(this);
  88383. };
  88384. return PlaneRotationGizmo;
  88385. }(BABYLON.Gizmo));
  88386. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  88387. })(BABYLON || (BABYLON = {}));
  88388. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  88389. var BABYLON;
  88390. (function (BABYLON) {
  88391. /**
  88392. * Gizmo that enables dragging a mesh along 3 axis
  88393. */
  88394. var PositionGizmo = /** @class */ (function (_super) {
  88395. __extends(PositionGizmo, _super);
  88396. /**
  88397. * Creates a PositionGizmo
  88398. * @param gizmoLayer The utility layer the gizmo will be added to
  88399. */
  88400. function PositionGizmo(gizmoLayer) {
  88401. var _this = _super.call(this, gizmoLayer) || this;
  88402. _this._xDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  88403. _this._yDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  88404. _this._zDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  88405. return _this;
  88406. }
  88407. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  88408. set: function (mesh) {
  88409. this._xDrag.attachedMesh = mesh;
  88410. this._yDrag.attachedMesh = mesh;
  88411. this._zDrag.attachedMesh = mesh;
  88412. },
  88413. enumerable: true,
  88414. configurable: true
  88415. });
  88416. PositionGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88417. this._xDrag.interactionsEnabled = value;
  88418. this._yDrag.interactionsEnabled = value;
  88419. this._zDrag.interactionsEnabled = value;
  88420. };
  88421. /**
  88422. * Disposes of the gizmo
  88423. */
  88424. PositionGizmo.prototype.dispose = function () {
  88425. this._xDrag.dispose();
  88426. this._yDrag.dispose();
  88427. this._zDrag.dispose();
  88428. };
  88429. return PositionGizmo;
  88430. }(BABYLON.Gizmo));
  88431. BABYLON.PositionGizmo = PositionGizmo;
  88432. })(BABYLON || (BABYLON = {}));
  88433. //# sourceMappingURL=babylon.positionGizmo.js.map
  88434. var BABYLON;
  88435. (function (BABYLON) {
  88436. /**
  88437. * Gizmo that enables rotating a mesh along 3 axis
  88438. */
  88439. var RotationGizmo = /** @class */ (function (_super) {
  88440. __extends(RotationGizmo, _super);
  88441. /**
  88442. * Creates a RotationGizmo
  88443. * @param gizmoLayer The utility layer the gizmo will be added to
  88444. */
  88445. function RotationGizmo(gizmoLayer) {
  88446. var _this = _super.call(this, gizmoLayer) || this;
  88447. _this._xDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  88448. _this._yDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  88449. _this._zDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  88450. return _this;
  88451. }
  88452. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  88453. set: function (mesh) {
  88454. this._xDrag.attachedMesh = mesh;
  88455. this._yDrag.attachedMesh = mesh;
  88456. this._zDrag.attachedMesh = mesh;
  88457. },
  88458. enumerable: true,
  88459. configurable: true
  88460. });
  88461. RotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88462. this._xDrag.interactionsEnabled = value;
  88463. this._yDrag.interactionsEnabled = value;
  88464. this._zDrag.interactionsEnabled = value;
  88465. };
  88466. /**
  88467. * Disposes of the gizmo
  88468. */
  88469. RotationGizmo.prototype.dispose = function () {
  88470. this._xDrag.dispose();
  88471. this._yDrag.dispose();
  88472. this._zDrag.dispose();
  88473. };
  88474. return RotationGizmo;
  88475. }(BABYLON.Gizmo));
  88476. BABYLON.RotationGizmo = RotationGizmo;
  88477. })(BABYLON || (BABYLON = {}));
  88478. //# sourceMappingURL=babylon.rotationGizmo.js.map
  88479. var BABYLON;
  88480. (function (BABYLON) {
  88481. /**
  88482. * Gizmo that enables scaling a mesh along 3 axis
  88483. */
  88484. var ScaleGizmo = /** @class */ (function (_super) {
  88485. __extends(ScaleGizmo, _super);
  88486. /**
  88487. * Creates a ScaleGizmo
  88488. * @param gizmoLayer The utility layer the gizmo will be added to
  88489. */
  88490. function ScaleGizmo(gizmoLayer) {
  88491. var _this = _super.call(this, gizmoLayer) || this;
  88492. _this._xDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  88493. _this._yDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  88494. _this._zDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  88495. return _this;
  88496. }
  88497. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  88498. set: function (mesh) {
  88499. this._xDrag.attachedMesh = mesh;
  88500. this._yDrag.attachedMesh = mesh;
  88501. this._zDrag.attachedMesh = mesh;
  88502. },
  88503. enumerable: true,
  88504. configurable: true
  88505. });
  88506. ScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88507. this._xDrag.interactionsEnabled = value;
  88508. this._yDrag.interactionsEnabled = value;
  88509. this._zDrag.interactionsEnabled = value;
  88510. };
  88511. /**
  88512. * Disposes of the gizmo
  88513. */
  88514. ScaleGizmo.prototype.dispose = function () {
  88515. this._xDrag.dispose();
  88516. this._yDrag.dispose();
  88517. this._zDrag.dispose();
  88518. };
  88519. return ScaleGizmo;
  88520. }(BABYLON.Gizmo));
  88521. BABYLON.ScaleGizmo = ScaleGizmo;
  88522. })(BABYLON || (BABYLON = {}));
  88523. //# sourceMappingURL=babylon.scaleGizmo.js.map
  88524. var BABYLON;
  88525. (function (BABYLON) {
  88526. /**
  88527. * Bounding box gizmo
  88528. */
  88529. var BoundingBoxGizmo = /** @class */ (function (_super) {
  88530. __extends(BoundingBoxGizmo, _super);
  88531. /**
  88532. * Creates an BoundingBoxGizmo
  88533. * @param gizmoLayer The utility layer the gizmo will be added to
  88534. * @param color The color of the gizmo
  88535. */
  88536. function BoundingBoxGizmo(gizmoLayer, color) {
  88537. var _this = _super.call(this, gizmoLayer) || this;
  88538. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  88539. _this._renderObserver = null;
  88540. _this._pointerObserver = null;
  88541. _this._scaleDragSpeed = 0.2;
  88542. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  88543. _this._updateScale = false;
  88544. // Create Materials
  88545. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88546. coloredMaterial.disableLighting = true;
  88547. coloredMaterial.emissiveColor = color;
  88548. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88549. hoverColoredMaterial.disableLighting = true;
  88550. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.2, 0.2, 0.2));
  88551. // Build bounding box out of lines
  88552. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  88553. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  88554. var lines = [];
  88555. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  88556. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  88557. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  88558. 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));
  88559. 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));
  88560. 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));
  88561. 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));
  88562. 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));
  88563. 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));
  88564. 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));
  88565. 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));
  88566. 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));
  88567. lines.forEach(function (l) {
  88568. l.color = color;
  88569. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  88570. l.isPickable = false;
  88571. _this._lineBoundingBox.addChild(l);
  88572. });
  88573. _this._rootMesh.addChild(_this._lineBoundingBox);
  88574. // Create rotation spheres
  88575. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  88576. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  88577. var _loop_1 = function (i_1) {
  88578. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 0.1 }, gizmoLayer.utilityLayerScene);
  88579. sphere.rotationQuaternion = new BABYLON.Quaternion();
  88580. sphere.material = coloredMaterial;
  88581. // Drag behavior
  88582. _dragBehavior = new BABYLON.PointerDragBehavior({});
  88583. _dragBehavior.moveAttached = false;
  88584. sphere.addBehavior(_dragBehavior);
  88585. _dragBehavior.onDragObservable.add(function (event) {
  88586. if (_this.attachedMesh) {
  88587. var worldDragDirection = sphere.forward;
  88588. // Project the world right on to the drag plane
  88589. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  88590. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  88591. // project drag delta on to the resulting drag axis and rotate based on that
  88592. var projectDist = BABYLON.Vector3.Dot(dragAxis, event.delta);
  88593. // Rotate based on axis
  88594. if (i_1 >= 8) {
  88595. _this.attachedMesh.rotation.z -= projectDist;
  88596. }
  88597. else if (i_1 >= 4) {
  88598. _this.attachedMesh.rotation.y -= projectDist;
  88599. }
  88600. else {
  88601. _this.attachedMesh.rotation.x -= projectDist;
  88602. }
  88603. }
  88604. });
  88605. // Selection/deselection
  88606. _dragBehavior.onDragStartObservable.add(function () {
  88607. _this._selectNode(sphere);
  88608. });
  88609. _dragBehavior.onDragEndObservable.add(function () {
  88610. _this._selectNode(null);
  88611. });
  88612. this_1._rotateSpheresParent.addChild(sphere);
  88613. };
  88614. var this_1 = this, _dragBehavior;
  88615. for (var i_1 = 0; i_1 < 12; i_1++) {
  88616. _loop_1(i_1);
  88617. }
  88618. _this._rootMesh.addChild(_this._rotateSpheresParent);
  88619. // Create scale cubes
  88620. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  88621. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  88622. for (var i = 0; i < 2; i++) {
  88623. for (var j = 0; j < 2; j++) {
  88624. var _loop_2 = function () {
  88625. var box = BABYLON.MeshBuilder.CreateBox("", { size: 0.1 }, gizmoLayer.utilityLayerScene);
  88626. box.material = coloredMaterial;
  88627. // Dragging logic
  88628. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  88629. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  88630. _dragBehavior.moveAttached = false;
  88631. box.addBehavior(_dragBehavior);
  88632. _dragBehavior.onDragObservable.add(function (event) {
  88633. if (_this.attachedMesh) {
  88634. // Current boudning box dimensions
  88635. var boundingInfo = _this.attachedMesh.getBoundingInfo().boundingBox;
  88636. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(_this.attachedMesh.scaling);
  88637. // Get the change in bounding box size/2 and add this to the mesh's position to offset from scaling with center pivot point
  88638. var deltaScale = new BABYLON.Vector3(event.dragDistance, event.dragDistance, event.dragDistance);
  88639. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  88640. var scaleRatio = deltaScale.divide(_this.attachedMesh.scaling).scaleInPlace(0.5);
  88641. var moveDirection = boundBoxDimensions.multiply(scaleRatio).multiplyInPlace(dragAxis);
  88642. var worldMoveDirection = BABYLON.Vector3.TransformCoordinates(moveDirection, _this.attachedMesh.getWorldMatrix().getRotationMatrix());
  88643. // Update scale and position
  88644. _this.attachedMesh.scaling.addInPlace(deltaScale);
  88645. _this.attachedMesh.position.addInPlace(worldMoveDirection);
  88646. }
  88647. });
  88648. // Selection/deselection
  88649. _dragBehavior.onDragStartObservable.add(function () {
  88650. _this._selectNode(box);
  88651. });
  88652. _dragBehavior.onDragEndObservable.add(function () {
  88653. _this._selectNode(null);
  88654. });
  88655. this_2._scaleBoxesParent.addChild(box);
  88656. };
  88657. var this_2 = this, _dragBehavior;
  88658. for (var k = 0; k < 2; k++) {
  88659. _loop_2();
  88660. }
  88661. }
  88662. }
  88663. _this._rootMesh.addChild(_this._scaleBoxesParent);
  88664. // Hover color change
  88665. var pointerIds = new Array();
  88666. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  88667. if (!pointerIds[pointerInfo.event.pointerId]) {
  88668. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  88669. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  88670. pointerIds[pointerInfo.event.pointerId] = mesh;
  88671. mesh.material = hoverColoredMaterial;
  88672. }
  88673. });
  88674. }
  88675. else {
  88676. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  88677. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  88678. delete pointerIds[pointerInfo.event.pointerId];
  88679. }
  88680. }
  88681. });
  88682. // Update bounding box positions
  88683. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  88684. _this._updateBoundingBox();
  88685. });
  88686. _this._updateBoundingBox();
  88687. return _this;
  88688. }
  88689. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  88690. this._rotateSpheresParent.getChildMeshes()
  88691. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  88692. m.isVisible = (!selectedMesh || m == selectedMesh);
  88693. });
  88694. };
  88695. BoundingBoxGizmo.prototype._updateBoundingBox = function () {
  88696. if (this.attachedMesh) {
  88697. // Update bounding dimensions/positions
  88698. var boundingInfo = this.attachedMesh.getBoundingInfo().boundingBox;
  88699. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(this.attachedMesh.scaling);
  88700. this._boundingDimensions.copyFrom(boundBoxDimensions);
  88701. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  88702. }
  88703. // Update rotation sphere locations
  88704. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  88705. for (var i = 0; i < 3; i++) {
  88706. for (var j = 0; j < 2; j++) {
  88707. for (var k = 0; k < 2; k++) {
  88708. var index = ((i * 4) + (j * 2)) + k;
  88709. if (i == 0) {
  88710. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  88711. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  88712. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  88713. }
  88714. if (i == 1) {
  88715. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  88716. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  88717. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  88718. }
  88719. if (i == 2) {
  88720. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  88721. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  88722. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  88723. }
  88724. }
  88725. }
  88726. }
  88727. // Update scale box locations
  88728. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  88729. for (var i = 0; i < 2; i++) {
  88730. for (var j = 0; j < 2; j++) {
  88731. for (var k = 0; k < 2; k++) {
  88732. var index = ((i * 4) + (j * 2)) + k;
  88733. if (scaleBoxes[index]) {
  88734. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  88735. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  88736. }
  88737. }
  88738. }
  88739. }
  88740. };
  88741. /**
  88742. * Disposes of the gizmo
  88743. */
  88744. BoundingBoxGizmo.prototype.dispose = function () {
  88745. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  88746. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  88747. this._lineBoundingBox.dispose();
  88748. this._rotateSpheresParent.dispose();
  88749. this._scaleBoxesParent.dispose();
  88750. _super.prototype.dispose.call(this);
  88751. };
  88752. return BoundingBoxGizmo;
  88753. }(BABYLON.Gizmo));
  88754. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  88755. })(BABYLON || (BABYLON = {}));
  88756. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  88757. var BABYLON;
  88758. (function (BABYLON) {
  88759. /**
  88760. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  88761. */
  88762. var GizmoManager = /** @class */ (function () {
  88763. /**
  88764. * Instatiates a gizmo manager
  88765. * @param scene the scene to overlay the gizmos on top of
  88766. * @param options If only a single gizmo should exist at one time
  88767. */
  88768. function GizmoManager(scene, options) {
  88769. var _this = this;
  88770. this.scene = scene;
  88771. // Set of gizmos that are currently in the scene for each mesh
  88772. this._gizmoSet = {};
  88773. this._pointerObserver = null;
  88774. this._gizmoLayer = new BABYLON.UtilityLayerRenderer(scene);
  88775. // Options parsing
  88776. if (!options) {
  88777. options = {};
  88778. }
  88779. if (options.singleGizmo === undefined) {
  88780. options.singleGizmo = true;
  88781. }
  88782. // Instatiate/dispose gizmos based on pointer actions
  88783. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  88784. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  88785. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  88786. if (!_this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId]) {
  88787. if (options.singleGizmo) {
  88788. _this._clearGizmos();
  88789. }
  88790. // Enable gizmo when mesh is selected
  88791. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId] = { positionGizmo: new BABYLON.PositionGizmo(_this._gizmoLayer), rotationGizmo: new BABYLON.RotationGizmo(_this._gizmoLayer) };
  88792. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  88793. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  88794. }
  88795. else {
  88796. if (!options.singleGizmo) {
  88797. // Disable gizmo when clicked again
  88798. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.dispose();
  88799. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.dispose();
  88800. delete _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId];
  88801. }
  88802. }
  88803. }
  88804. else {
  88805. if (options.singleGizmo) {
  88806. // Disable gizmo when clicked away
  88807. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  88808. var gizmoPick = _this._gizmoLayer.utilityLayerScene.pickWithRay(pointerInfo.pickInfo.ray);
  88809. if (gizmoPick && !gizmoPick.hit) {
  88810. _this._clearGizmos();
  88811. }
  88812. }
  88813. }
  88814. }
  88815. }
  88816. });
  88817. }
  88818. /**
  88819. * Disposes of the gizmo manager
  88820. */
  88821. GizmoManager.prototype.dispose = function () {
  88822. this.scene.onPointerObservable.remove(this._pointerObserver);
  88823. this._clearGizmos();
  88824. this._gizmoLayer.dispose();
  88825. };
  88826. GizmoManager.prototype._clearGizmos = function () {
  88827. for (var key in this._gizmoSet) {
  88828. if (this._gizmoSet.hasOwnProperty(key)) {
  88829. this._gizmoSet[key].positionGizmo.dispose();
  88830. this._gizmoSet[key].rotationGizmo.dispose();
  88831. delete this._gizmoSet[key];
  88832. }
  88833. }
  88834. };
  88835. return GizmoManager;
  88836. }());
  88837. BABYLON.GizmoManager = GizmoManager;
  88838. })(BABYLON || (BABYLON = {}));
  88839. //# sourceMappingURL=babylon.gizmoManager.js.map
  88840. var BABYLON;
  88841. (function (BABYLON) {
  88842. /**
  88843. * Defines a target to use with MorphTargetManager
  88844. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  88845. */
  88846. var MorphTarget = /** @class */ (function () {
  88847. /**
  88848. * Creates a new MorphTarget
  88849. * @param name defines the name of the target
  88850. * @param influence defines the influence to use
  88851. */
  88852. function MorphTarget(
  88853. /** defines the name of the target */
  88854. name, influence, scene) {
  88855. if (influence === void 0) { influence = 0; }
  88856. if (scene === void 0) { scene = null; }
  88857. this.name = name;
  88858. /**
  88859. * Gets or sets the list of animations
  88860. */
  88861. this.animations = new Array();
  88862. this._positions = null;
  88863. this._normals = null;
  88864. this._tangents = null;
  88865. /**
  88866. * Observable raised when the influence changes
  88867. */
  88868. this.onInfluenceChanged = new BABYLON.Observable();
  88869. this._animationPropertiesOverride = null;
  88870. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88871. this.influence = influence;
  88872. }
  88873. Object.defineProperty(MorphTarget.prototype, "influence", {
  88874. /**
  88875. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  88876. */
  88877. get: function () {
  88878. return this._influence;
  88879. },
  88880. set: function (influence) {
  88881. if (this._influence === influence) {
  88882. return;
  88883. }
  88884. var previous = this._influence;
  88885. this._influence = influence;
  88886. if (this.onInfluenceChanged.hasObservers) {
  88887. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  88888. }
  88889. },
  88890. enumerable: true,
  88891. configurable: true
  88892. });
  88893. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  88894. /**
  88895. * Gets or sets the animation properties override
  88896. */
  88897. get: function () {
  88898. if (!this._animationPropertiesOverride && this._scene) {
  88899. return this._scene.animationPropertiesOverride;
  88900. }
  88901. return this._animationPropertiesOverride;
  88902. },
  88903. set: function (value) {
  88904. this._animationPropertiesOverride = value;
  88905. },
  88906. enumerable: true,
  88907. configurable: true
  88908. });
  88909. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  88910. /**
  88911. * Gets a boolean defining if the target contains position data
  88912. */
  88913. get: function () {
  88914. return !!this._positions;
  88915. },
  88916. enumerable: true,
  88917. configurable: true
  88918. });
  88919. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  88920. /**
  88921. * Gets a boolean defining if the target contains normal data
  88922. */
  88923. get: function () {
  88924. return !!this._normals;
  88925. },
  88926. enumerable: true,
  88927. configurable: true
  88928. });
  88929. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  88930. /**
  88931. * Gets a boolean defining if the target contains tangent data
  88932. */
  88933. get: function () {
  88934. return !!this._tangents;
  88935. },
  88936. enumerable: true,
  88937. configurable: true
  88938. });
  88939. /**
  88940. * Affects position data to this target
  88941. * @param data defines the position data to use
  88942. */
  88943. MorphTarget.prototype.setPositions = function (data) {
  88944. this._positions = data;
  88945. };
  88946. /**
  88947. * Gets the position data stored in this target
  88948. * @returns a FloatArray containing the position data (or null if not present)
  88949. */
  88950. MorphTarget.prototype.getPositions = function () {
  88951. return this._positions;
  88952. };
  88953. /**
  88954. * Affects normal data to this target
  88955. * @param data defines the normal data to use
  88956. */
  88957. MorphTarget.prototype.setNormals = function (data) {
  88958. this._normals = data;
  88959. };
  88960. /**
  88961. * Gets the normal data stored in this target
  88962. * @returns a FloatArray containing the normal data (or null if not present)
  88963. */
  88964. MorphTarget.prototype.getNormals = function () {
  88965. return this._normals;
  88966. };
  88967. /**
  88968. * Affects tangent data to this target
  88969. * @param data defines the tangent data to use
  88970. */
  88971. MorphTarget.prototype.setTangents = function (data) {
  88972. this._tangents = data;
  88973. };
  88974. /**
  88975. * Gets the tangent data stored in this target
  88976. * @returns a FloatArray containing the tangent data (or null if not present)
  88977. */
  88978. MorphTarget.prototype.getTangents = function () {
  88979. return this._tangents;
  88980. };
  88981. /**
  88982. * Serializes the current target into a Serialization object
  88983. * @returns the serialized object
  88984. */
  88985. MorphTarget.prototype.serialize = function () {
  88986. var serializationObject = {};
  88987. serializationObject.name = this.name;
  88988. serializationObject.influence = this.influence;
  88989. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  88990. if (this.hasNormals) {
  88991. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  88992. }
  88993. if (this.hasTangents) {
  88994. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  88995. }
  88996. // Animations
  88997. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  88998. return serializationObject;
  88999. };
  89000. // Statics
  89001. /**
  89002. * Creates a new target from serialized data
  89003. * @param serializationObject defines the serialized data to use
  89004. * @returns a new MorphTarget
  89005. */
  89006. MorphTarget.Parse = function (serializationObject) {
  89007. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  89008. result.setPositions(serializationObject.positions);
  89009. if (serializationObject.normals) {
  89010. result.setNormals(serializationObject.normals);
  89011. }
  89012. if (serializationObject.tangents) {
  89013. result.setTangents(serializationObject.tangents);
  89014. }
  89015. // Animations
  89016. if (serializationObject.animations) {
  89017. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  89018. var parsedAnimation = serializationObject.animations[animationIndex];
  89019. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  89020. }
  89021. }
  89022. return result;
  89023. };
  89024. /**
  89025. * Creates a MorphTarget from mesh data
  89026. * @param mesh defines the source mesh
  89027. * @param name defines the name to use for the new target
  89028. * @param influence defines the influence to attach to the target
  89029. * @returns a new MorphTarget
  89030. */
  89031. MorphTarget.FromMesh = function (mesh, name, influence) {
  89032. if (!name) {
  89033. name = mesh.name;
  89034. }
  89035. var result = new MorphTarget(name, influence, mesh.getScene());
  89036. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  89037. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  89038. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  89039. }
  89040. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  89041. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  89042. }
  89043. return result;
  89044. };
  89045. return MorphTarget;
  89046. }());
  89047. BABYLON.MorphTarget = MorphTarget;
  89048. })(BABYLON || (BABYLON = {}));
  89049. //# sourceMappingURL=babylon.morphTarget.js.map
  89050. var BABYLON;
  89051. (function (BABYLON) {
  89052. /**
  89053. * This class is used to deform meshes using morphing between different targets
  89054. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  89055. */
  89056. var MorphTargetManager = /** @class */ (function () {
  89057. /**
  89058. * Creates a new MorphTargetManager
  89059. * @param scene defines the current scene
  89060. */
  89061. function MorphTargetManager(scene) {
  89062. if (scene === void 0) { scene = null; }
  89063. this._targets = new Array();
  89064. this._targetObservable = new Array();
  89065. this._activeTargets = new BABYLON.SmartArray(16);
  89066. this._supportsNormals = false;
  89067. this._supportsTangents = false;
  89068. this._vertexCount = 0;
  89069. this._uniqueId = 0;
  89070. this._tempInfluences = new Array();
  89071. if (!scene) {
  89072. scene = BABYLON.Engine.LastCreatedScene;
  89073. }
  89074. this._scene = scene;
  89075. if (this._scene) {
  89076. this._scene.morphTargetManagers.push(this);
  89077. this._uniqueId = this._scene.getUniqueId();
  89078. }
  89079. }
  89080. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  89081. /**
  89082. * Gets the unique ID of this manager
  89083. */
  89084. get: function () {
  89085. return this._uniqueId;
  89086. },
  89087. enumerable: true,
  89088. configurable: true
  89089. });
  89090. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  89091. /**
  89092. * Gets the number of vertices handled by this manager
  89093. */
  89094. get: function () {
  89095. return this._vertexCount;
  89096. },
  89097. enumerable: true,
  89098. configurable: true
  89099. });
  89100. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  89101. /**
  89102. * Gets a boolean indicating if this manager supports morphing of normals
  89103. */
  89104. get: function () {
  89105. return this._supportsNormals;
  89106. },
  89107. enumerable: true,
  89108. configurable: true
  89109. });
  89110. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  89111. /**
  89112. * Gets a boolean indicating if this manager supports morphing of tangents
  89113. */
  89114. get: function () {
  89115. return this._supportsTangents;
  89116. },
  89117. enumerable: true,
  89118. configurable: true
  89119. });
  89120. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  89121. /**
  89122. * Gets the number of targets stored in this manager
  89123. */
  89124. get: function () {
  89125. return this._targets.length;
  89126. },
  89127. enumerable: true,
  89128. configurable: true
  89129. });
  89130. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  89131. /**
  89132. * Gets the number of influencers (ie. the number of targets with influences > 0)
  89133. */
  89134. get: function () {
  89135. return this._activeTargets.length;
  89136. },
  89137. enumerable: true,
  89138. configurable: true
  89139. });
  89140. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  89141. /**
  89142. * Gets the list of influences (one per target)
  89143. */
  89144. get: function () {
  89145. return this._influences;
  89146. },
  89147. enumerable: true,
  89148. configurable: true
  89149. });
  89150. /**
  89151. * Gets the active target at specified index. An active target is a target with an influence > 0
  89152. * @param index defines the index to check
  89153. * @returns the requested target
  89154. */
  89155. MorphTargetManager.prototype.getActiveTarget = function (index) {
  89156. return this._activeTargets.data[index];
  89157. };
  89158. /**
  89159. * Gets the target at specified index
  89160. * @param index defines the index to check
  89161. * @returns the requested target
  89162. */
  89163. MorphTargetManager.prototype.getTarget = function (index) {
  89164. return this._targets[index];
  89165. };
  89166. /**
  89167. * Add a new target to this manager
  89168. * @param target defines the target to add
  89169. */
  89170. MorphTargetManager.prototype.addTarget = function (target) {
  89171. var _this = this;
  89172. this._targets.push(target);
  89173. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  89174. _this._syncActiveTargets(needUpdate);
  89175. }));
  89176. this._syncActiveTargets(true);
  89177. };
  89178. /**
  89179. * Removes a target from the manager
  89180. * @param target defines the target to remove
  89181. */
  89182. MorphTargetManager.prototype.removeTarget = function (target) {
  89183. var index = this._targets.indexOf(target);
  89184. if (index >= 0) {
  89185. this._targets.splice(index, 1);
  89186. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  89187. this._syncActiveTargets(true);
  89188. }
  89189. };
  89190. /**
  89191. * Serializes the current manager into a Serialization object
  89192. * @returns the serialized object
  89193. */
  89194. MorphTargetManager.prototype.serialize = function () {
  89195. var serializationObject = {};
  89196. serializationObject.id = this.uniqueId;
  89197. serializationObject.targets = [];
  89198. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  89199. var target = _a[_i];
  89200. serializationObject.targets.push(target.serialize());
  89201. }
  89202. return serializationObject;
  89203. };
  89204. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  89205. var influenceCount = 0;
  89206. this._activeTargets.reset();
  89207. this._supportsNormals = true;
  89208. this._supportsTangents = true;
  89209. this._vertexCount = 0;
  89210. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  89211. var target = _a[_i];
  89212. this._activeTargets.push(target);
  89213. this._tempInfluences[influenceCount++] = target.influence;
  89214. var positions = target.getPositions();
  89215. if (positions) {
  89216. this._supportsNormals = this._supportsNormals && target.hasNormals;
  89217. this._supportsTangents = this._supportsTangents && target.hasTangents;
  89218. var vertexCount = positions.length / 3;
  89219. if (this._vertexCount === 0) {
  89220. this._vertexCount = vertexCount;
  89221. }
  89222. else if (this._vertexCount !== vertexCount) {
  89223. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  89224. return;
  89225. }
  89226. }
  89227. }
  89228. if (!this._influences || this._influences.length !== influenceCount) {
  89229. this._influences = new Float32Array(influenceCount);
  89230. }
  89231. for (var index = 0; index < influenceCount; index++) {
  89232. this._influences[index] = this._tempInfluences[index];
  89233. }
  89234. if (needUpdate) {
  89235. this.synchronize();
  89236. }
  89237. };
  89238. /**
  89239. * Syncrhonize the targets with all the meshes using this morph target manager
  89240. */
  89241. MorphTargetManager.prototype.synchronize = function () {
  89242. if (!this._scene) {
  89243. return;
  89244. }
  89245. // Flag meshes as dirty to resync with the active targets
  89246. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  89247. var mesh = _a[_i];
  89248. if (mesh.morphTargetManager === this) {
  89249. mesh._syncGeometryWithMorphTargetManager();
  89250. }
  89251. }
  89252. };
  89253. // Statics
  89254. /**
  89255. * Creates a new MorphTargetManager from serialized data
  89256. * @param serializationObject defines the serialized data
  89257. * @param scene defines the hosting scene
  89258. * @returns the new MorphTargetManager
  89259. */
  89260. MorphTargetManager.Parse = function (serializationObject, scene) {
  89261. var result = new MorphTargetManager(scene);
  89262. result._uniqueId = serializationObject.id;
  89263. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  89264. var targetData = _a[_i];
  89265. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  89266. }
  89267. return result;
  89268. };
  89269. return MorphTargetManager;
  89270. }());
  89271. BABYLON.MorphTargetManager = MorphTargetManager;
  89272. })(BABYLON || (BABYLON = {}));
  89273. //# sourceMappingURL=babylon.morphTargetManager.js.map
  89274. var BABYLON;
  89275. (function (BABYLON) {
  89276. var Octree = /** @class */ (function () {
  89277. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  89278. if (maxDepth === void 0) { maxDepth = 2; }
  89279. this.maxDepth = maxDepth;
  89280. this.dynamicContent = new Array();
  89281. this._maxBlockCapacity = maxBlockCapacity || 64;
  89282. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  89283. this._creationFunc = creationFunc;
  89284. }
  89285. // Methods
  89286. Octree.prototype.update = function (worldMin, worldMax, entries) {
  89287. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  89288. };
  89289. Octree.prototype.addMesh = function (entry) {
  89290. for (var index = 0; index < this.blocks.length; index++) {
  89291. var block = this.blocks[index];
  89292. block.addEntry(entry);
  89293. }
  89294. };
  89295. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  89296. this._selectionContent.reset();
  89297. for (var index = 0; index < this.blocks.length; index++) {
  89298. var block = this.blocks[index];
  89299. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  89300. }
  89301. if (allowDuplicate) {
  89302. this._selectionContent.concat(this.dynamicContent);
  89303. }
  89304. else {
  89305. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  89306. }
  89307. return this._selectionContent;
  89308. };
  89309. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  89310. this._selectionContent.reset();
  89311. for (var index = 0; index < this.blocks.length; index++) {
  89312. var block = this.blocks[index];
  89313. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  89314. }
  89315. if (allowDuplicate) {
  89316. this._selectionContent.concat(this.dynamicContent);
  89317. }
  89318. else {
  89319. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  89320. }
  89321. return this._selectionContent;
  89322. };
  89323. Octree.prototype.intersectsRay = function (ray) {
  89324. this._selectionContent.reset();
  89325. for (var index = 0; index < this.blocks.length; index++) {
  89326. var block = this.blocks[index];
  89327. block.intersectsRay(ray, this._selectionContent);
  89328. }
  89329. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  89330. return this._selectionContent;
  89331. };
  89332. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  89333. target.blocks = new Array();
  89334. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  89335. // Segmenting space
  89336. for (var x = 0; x < 2; x++) {
  89337. for (var y = 0; y < 2; y++) {
  89338. for (var z = 0; z < 2; z++) {
  89339. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  89340. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  89341. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  89342. block.addEntries(entries);
  89343. target.blocks.push(block);
  89344. }
  89345. }
  89346. }
  89347. };
  89348. Octree.CreationFuncForMeshes = function (entry, block) {
  89349. var boundingInfo = entry.getBoundingInfo();
  89350. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  89351. block.entries.push(entry);
  89352. }
  89353. };
  89354. Octree.CreationFuncForSubMeshes = function (entry, block) {
  89355. var boundingInfo = entry.getBoundingInfo();
  89356. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  89357. block.entries.push(entry);
  89358. }
  89359. };
  89360. return Octree;
  89361. }());
  89362. BABYLON.Octree = Octree;
  89363. })(BABYLON || (BABYLON = {}));
  89364. //# sourceMappingURL=babylon.octree.js.map
  89365. var BABYLON;
  89366. (function (BABYLON) {
  89367. var OctreeBlock = /** @class */ (function () {
  89368. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  89369. this.entries = new Array();
  89370. this._boundingVectors = new Array();
  89371. this._capacity = capacity;
  89372. this._depth = depth;
  89373. this._maxDepth = maxDepth;
  89374. this._creationFunc = creationFunc;
  89375. this._minPoint = minPoint;
  89376. this._maxPoint = maxPoint;
  89377. this._boundingVectors.push(minPoint.clone());
  89378. this._boundingVectors.push(maxPoint.clone());
  89379. this._boundingVectors.push(minPoint.clone());
  89380. this._boundingVectors[2].x = maxPoint.x;
  89381. this._boundingVectors.push(minPoint.clone());
  89382. this._boundingVectors[3].y = maxPoint.y;
  89383. this._boundingVectors.push(minPoint.clone());
  89384. this._boundingVectors[4].z = maxPoint.z;
  89385. this._boundingVectors.push(maxPoint.clone());
  89386. this._boundingVectors[5].z = minPoint.z;
  89387. this._boundingVectors.push(maxPoint.clone());
  89388. this._boundingVectors[6].x = minPoint.x;
  89389. this._boundingVectors.push(maxPoint.clone());
  89390. this._boundingVectors[7].y = minPoint.y;
  89391. }
  89392. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  89393. // Property
  89394. get: function () {
  89395. return this._capacity;
  89396. },
  89397. enumerable: true,
  89398. configurable: true
  89399. });
  89400. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  89401. get: function () {
  89402. return this._minPoint;
  89403. },
  89404. enumerable: true,
  89405. configurable: true
  89406. });
  89407. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  89408. get: function () {
  89409. return this._maxPoint;
  89410. },
  89411. enumerable: true,
  89412. configurable: true
  89413. });
  89414. // Methods
  89415. OctreeBlock.prototype.addEntry = function (entry) {
  89416. if (this.blocks) {
  89417. for (var index = 0; index < this.blocks.length; index++) {
  89418. var block = this.blocks[index];
  89419. block.addEntry(entry);
  89420. }
  89421. return;
  89422. }
  89423. this._creationFunc(entry, this);
  89424. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  89425. this.createInnerBlocks();
  89426. }
  89427. };
  89428. OctreeBlock.prototype.addEntries = function (entries) {
  89429. for (var index = 0; index < entries.length; index++) {
  89430. var mesh = entries[index];
  89431. this.addEntry(mesh);
  89432. }
  89433. };
  89434. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  89435. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  89436. if (this.blocks) {
  89437. for (var index = 0; index < this.blocks.length; index++) {
  89438. var block = this.blocks[index];
  89439. block.select(frustumPlanes, selection, allowDuplicate);
  89440. }
  89441. return;
  89442. }
  89443. if (allowDuplicate) {
  89444. selection.concat(this.entries);
  89445. }
  89446. else {
  89447. selection.concatWithNoDuplicate(this.entries);
  89448. }
  89449. }
  89450. };
  89451. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  89452. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  89453. if (this.blocks) {
  89454. for (var index = 0; index < this.blocks.length; index++) {
  89455. var block = this.blocks[index];
  89456. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  89457. }
  89458. return;
  89459. }
  89460. if (allowDuplicate) {
  89461. selection.concat(this.entries);
  89462. }
  89463. else {
  89464. selection.concatWithNoDuplicate(this.entries);
  89465. }
  89466. }
  89467. };
  89468. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  89469. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  89470. if (this.blocks) {
  89471. for (var index = 0; index < this.blocks.length; index++) {
  89472. var block = this.blocks[index];
  89473. block.intersectsRay(ray, selection);
  89474. }
  89475. return;
  89476. }
  89477. selection.concatWithNoDuplicate(this.entries);
  89478. }
  89479. };
  89480. OctreeBlock.prototype.createInnerBlocks = function () {
  89481. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  89482. };
  89483. return OctreeBlock;
  89484. }());
  89485. BABYLON.OctreeBlock = OctreeBlock;
  89486. })(BABYLON || (BABYLON = {}));
  89487. //# sourceMappingURL=babylon.octreeBlock.js.map
  89488. var BABYLON;
  89489. (function (BABYLON) {
  89490. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  89491. __extends(VRDistortionCorrectionPostProcess, _super);
  89492. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  89493. var _this = _super.call(this, name, "vrDistortionCorrection", [
  89494. 'LensCenter',
  89495. 'Scale',
  89496. 'ScaleIn',
  89497. 'HmdWarpParam'
  89498. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  89499. _this._isRightEye = isRightEye;
  89500. _this._distortionFactors = vrMetrics.distortionK;
  89501. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  89502. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  89503. _this.adaptScaleToCurrentViewport = true;
  89504. _this.onSizeChangedObservable.add(function () {
  89505. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  89506. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  89507. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  89508. });
  89509. _this.onApplyObservable.add(function (effect) {
  89510. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  89511. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  89512. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  89513. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  89514. });
  89515. return _this;
  89516. }
  89517. return VRDistortionCorrectionPostProcess;
  89518. }(BABYLON.PostProcess));
  89519. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  89520. })(BABYLON || (BABYLON = {}));
  89521. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  89522. var BABYLON;
  89523. (function (BABYLON) {
  89524. /**
  89525. * Postprocess used to generate anaglyphic rendering
  89526. */
  89527. var AnaglyphPostProcess = /** @class */ (function (_super) {
  89528. __extends(AnaglyphPostProcess, _super);
  89529. /**
  89530. * Creates a new AnaglyphPostProcess
  89531. * @param name defines postprocess name
  89532. * @param options defines creation options or target ratio scale
  89533. * @param rigCameras defines cameras using this postprocess
  89534. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  89535. * @param engine defines hosting engine
  89536. * @param reusable defines if the postprocess will be reused multiple times per frame
  89537. */
  89538. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  89539. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  89540. _this._passedProcess = rigCameras[0]._rigPostProcess;
  89541. _this.onApplyObservable.add(function (effect) {
  89542. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  89543. });
  89544. return _this;
  89545. }
  89546. return AnaglyphPostProcess;
  89547. }(BABYLON.PostProcess));
  89548. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  89549. })(BABYLON || (BABYLON = {}));
  89550. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  89551. var BABYLON;
  89552. (function (BABYLON) {
  89553. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  89554. __extends(StereoscopicInterlacePostProcess, _super);
  89555. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  89556. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  89557. _this._passedProcess = rigCameras[0]._rigPostProcess;
  89558. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  89559. _this.onSizeChangedObservable.add(function () {
  89560. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  89561. });
  89562. _this.onApplyObservable.add(function (effect) {
  89563. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  89564. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  89565. });
  89566. return _this;
  89567. }
  89568. return StereoscopicInterlacePostProcess;
  89569. }(BABYLON.PostProcess));
  89570. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  89571. })(BABYLON || (BABYLON = {}));
  89572. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  89573. var BABYLON;
  89574. (function (BABYLON) {
  89575. /**
  89576. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  89577. * Screen rotation is taken into account.
  89578. */
  89579. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  89580. function FreeCameraDeviceOrientationInput() {
  89581. var _this = this;
  89582. this._screenOrientationAngle = 0;
  89583. this._screenQuaternion = new BABYLON.Quaternion();
  89584. this._alpha = 0;
  89585. this._beta = 0;
  89586. this._gamma = 0;
  89587. this._orientationChanged = function () {
  89588. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  89589. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  89590. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  89591. };
  89592. this._deviceOrientation = function (evt) {
  89593. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  89594. _this._beta = evt.beta !== null ? evt.beta : 0;
  89595. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  89596. };
  89597. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  89598. this._orientationChanged();
  89599. }
  89600. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  89601. get: function () {
  89602. return this._camera;
  89603. },
  89604. set: function (camera) {
  89605. this._camera = camera;
  89606. if (this._camera != null && !this._camera.rotationQuaternion) {
  89607. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  89608. }
  89609. },
  89610. enumerable: true,
  89611. configurable: true
  89612. });
  89613. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  89614. window.addEventListener("orientationchange", this._orientationChanged);
  89615. window.addEventListener("deviceorientation", this._deviceOrientation);
  89616. //In certain cases, the attach control is called AFTER orientation was changed,
  89617. //So this is needed.
  89618. this._orientationChanged();
  89619. };
  89620. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  89621. window.removeEventListener("orientationchange", this._orientationChanged);
  89622. window.removeEventListener("deviceorientation", this._deviceOrientation);
  89623. };
  89624. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  89625. //if no device orientation provided, don't update the rotation.
  89626. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  89627. if (!this._alpha)
  89628. return;
  89629. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  89630. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  89631. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  89632. //Mirror on XY Plane
  89633. this._camera.rotationQuaternion.z *= -1;
  89634. this._camera.rotationQuaternion.w *= -1;
  89635. };
  89636. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  89637. return "FreeCameraDeviceOrientationInput";
  89638. };
  89639. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  89640. return "deviceOrientation";
  89641. };
  89642. return FreeCameraDeviceOrientationInput;
  89643. }());
  89644. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  89645. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  89646. })(BABYLON || (BABYLON = {}));
  89647. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  89648. var BABYLON;
  89649. (function (BABYLON) {
  89650. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  89651. function ArcRotateCameraVRDeviceOrientationInput() {
  89652. this.alphaCorrection = 1;
  89653. this.betaCorrection = 1;
  89654. this.gammaCorrection = 1;
  89655. this._alpha = 0;
  89656. this._gamma = 0;
  89657. this._dirty = false;
  89658. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  89659. }
  89660. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  89661. this.camera.attachControl(element, noPreventDefault);
  89662. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  89663. };
  89664. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  89665. if (evt.alpha !== null) {
  89666. this._alpha = +evt.alpha | 0;
  89667. }
  89668. if (evt.gamma !== null) {
  89669. this._gamma = +evt.gamma | 0;
  89670. }
  89671. this._dirty = true;
  89672. };
  89673. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  89674. if (this._dirty) {
  89675. this._dirty = false;
  89676. if (this._gamma < 0) {
  89677. this._gamma = 180 + this._gamma;
  89678. }
  89679. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  89680. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  89681. }
  89682. };
  89683. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  89684. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  89685. };
  89686. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  89687. return "ArcRotateCameraVRDeviceOrientationInput";
  89688. };
  89689. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  89690. return "VRDeviceOrientation";
  89691. };
  89692. return ArcRotateCameraVRDeviceOrientationInput;
  89693. }());
  89694. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  89695. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  89696. })(BABYLON || (BABYLON = {}));
  89697. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  89698. var BABYLON;
  89699. (function (BABYLON) {
  89700. var VRCameraMetrics = /** @class */ (function () {
  89701. function VRCameraMetrics() {
  89702. this.compensateDistortion = true;
  89703. }
  89704. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  89705. get: function () {
  89706. return this.hResolution / (2 * this.vResolution);
  89707. },
  89708. enumerable: true,
  89709. configurable: true
  89710. });
  89711. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  89712. get: function () {
  89713. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  89714. },
  89715. enumerable: true,
  89716. configurable: true
  89717. });
  89718. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  89719. get: function () {
  89720. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  89721. var h = (4 * meters) / this.hScreenSize;
  89722. return BABYLON.Matrix.Translation(h, 0, 0);
  89723. },
  89724. enumerable: true,
  89725. configurable: true
  89726. });
  89727. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  89728. get: function () {
  89729. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  89730. var h = (4 * meters) / this.hScreenSize;
  89731. return BABYLON.Matrix.Translation(-h, 0, 0);
  89732. },
  89733. enumerable: true,
  89734. configurable: true
  89735. });
  89736. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  89737. get: function () {
  89738. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  89739. },
  89740. enumerable: true,
  89741. configurable: true
  89742. });
  89743. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  89744. get: function () {
  89745. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  89746. },
  89747. enumerable: true,
  89748. configurable: true
  89749. });
  89750. VRCameraMetrics.GetDefault = function () {
  89751. var result = new VRCameraMetrics();
  89752. result.hResolution = 1280;
  89753. result.vResolution = 800;
  89754. result.hScreenSize = 0.149759993;
  89755. result.vScreenSize = 0.0935999975;
  89756. result.vScreenCenter = 0.0467999987;
  89757. result.eyeToScreenDistance = 0.0410000011;
  89758. result.lensSeparationDistance = 0.0635000020;
  89759. result.interpupillaryDistance = 0.0640000030;
  89760. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  89761. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  89762. result.postProcessScaleFactor = 1.714605507808412;
  89763. result.lensCenterOffset = 0.151976421;
  89764. return result;
  89765. };
  89766. return VRCameraMetrics;
  89767. }());
  89768. BABYLON.VRCameraMetrics = VRCameraMetrics;
  89769. })(BABYLON || (BABYLON = {}));
  89770. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  89771. var BABYLON;
  89772. (function (BABYLON) {
  89773. /**
  89774. * This represents a WebVR camera.
  89775. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  89776. * @example http://doc.babylonjs.com/how_to/webvr_camera
  89777. */
  89778. var WebVRFreeCamera = /** @class */ (function (_super) {
  89779. __extends(WebVRFreeCamera, _super);
  89780. /**
  89781. * Instantiates a WebVRFreeCamera.
  89782. * @param name The name of the WebVRFreeCamera
  89783. * @param position The starting anchor position for the camera
  89784. * @param scene The scene the camera belongs to
  89785. * @param webVROptions a set of customizable options for the webVRCamera
  89786. */
  89787. function WebVRFreeCamera(name, position, scene, webVROptions) {
  89788. if (webVROptions === void 0) { webVROptions = {}; }
  89789. var _this = _super.call(this, name, position, scene) || this;
  89790. _this.webVROptions = webVROptions;
  89791. /**
  89792. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  89793. */
  89794. _this._vrDevice = null;
  89795. /**
  89796. * The rawPose of the vrDevice.
  89797. */
  89798. _this.rawPose = null;
  89799. _this._specsVersion = "1.1";
  89800. _this._attached = false;
  89801. _this._descendants = [];
  89802. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  89803. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  89804. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  89805. _this._standingMatrix = null;
  89806. /**
  89807. * Represents device position in babylon space.
  89808. */
  89809. _this.devicePosition = BABYLON.Vector3.Zero();
  89810. /**
  89811. * Represents device rotation in babylon space.
  89812. */
  89813. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  89814. /**
  89815. * The scale of the device to be used when translating from device space to babylon space.
  89816. */
  89817. _this.deviceScaleFactor = 1;
  89818. _this._deviceToWorld = BABYLON.Matrix.Identity();
  89819. _this._worldToDevice = BABYLON.Matrix.Identity();
  89820. /**
  89821. * References to the webVR controllers for the vrDevice.
  89822. */
  89823. _this.controllers = [];
  89824. /**
  89825. * Emits an event when a controller is attached.
  89826. */
  89827. _this.onControllersAttachedObservable = new BABYLON.Observable();
  89828. /**
  89829. * Emits an event when a controller's mesh has been loaded;
  89830. */
  89831. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  89832. /**
  89833. * If the rig cameras be used as parent instead of this camera.
  89834. */
  89835. _this.rigParenting = true;
  89836. _this._defaultHeight = undefined;
  89837. _this._workingVector = BABYLON.Vector3.Zero();
  89838. _this._oneVector = BABYLON.Vector3.One();
  89839. _this._workingMatrix = BABYLON.Matrix.Identity();
  89840. _this._cache.position = BABYLON.Vector3.Zero();
  89841. if (webVROptions.defaultHeight) {
  89842. _this._defaultHeight = webVROptions.defaultHeight;
  89843. _this.position.y = _this._defaultHeight;
  89844. }
  89845. _this.minZ = 0.1;
  89846. //legacy support - the compensation boolean was removed.
  89847. if (arguments.length === 5) {
  89848. _this.webVROptions = arguments[4];
  89849. }
  89850. // default webVR options
  89851. if (_this.webVROptions.trackPosition == undefined) {
  89852. _this.webVROptions.trackPosition = true;
  89853. }
  89854. if (_this.webVROptions.controllerMeshes == undefined) {
  89855. _this.webVROptions.controllerMeshes = true;
  89856. }
  89857. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  89858. _this.webVROptions.defaultLightingOnControllers = true;
  89859. }
  89860. _this.rotationQuaternion = new BABYLON.Quaternion();
  89861. if (_this.webVROptions && _this.webVROptions.positionScale) {
  89862. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  89863. }
  89864. //enable VR
  89865. var engine = _this.getEngine();
  89866. _this._onVREnabled = function (success) { if (success) {
  89867. _this.initControllers();
  89868. } };
  89869. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  89870. engine.initWebVR().add(function (event) {
  89871. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  89872. return;
  89873. }
  89874. _this._vrDevice = event.vrDisplay;
  89875. //reset the rig parameters.
  89876. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  89877. if (_this._attached) {
  89878. _this.getEngine().enableVR();
  89879. }
  89880. });
  89881. if (typeof (VRFrameData) !== "undefined")
  89882. _this._frameData = new VRFrameData();
  89883. /**
  89884. * The idea behind the following lines:
  89885. * objects that have the camera as parent should actually have the rig cameras as a parent.
  89886. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  89887. * the second will not show it correctly.
  89888. *
  89889. * To solve this - each object that has the camera as parent will be added to a protected array.
  89890. * When the rig camera renders, it will take this array and set all of those to be its children.
  89891. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  89892. * Amazing!
  89893. */
  89894. scene.onBeforeCameraRenderObservable.add(function (camera) {
  89895. if (camera.parent === _this && _this.rigParenting) {
  89896. _this._descendants = _this.getDescendants(true, function (n) {
  89897. // don't take the cameras or the controllers!
  89898. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  89899. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  89900. return !isController && !isRigCamera;
  89901. });
  89902. _this._descendants.forEach(function (node) {
  89903. node.parent = camera;
  89904. });
  89905. }
  89906. });
  89907. scene.onAfterCameraRenderObservable.add(function (camera) {
  89908. if (camera.parent === _this && _this.rigParenting) {
  89909. _this._descendants.forEach(function (node) {
  89910. node.parent = _this;
  89911. });
  89912. }
  89913. });
  89914. return _this;
  89915. }
  89916. /**
  89917. * Gets the device distance from the ground in meters.
  89918. * @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.
  89919. */
  89920. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  89921. if (this._standingMatrix) {
  89922. // Add standing matrix offset to get real offset from ground in room
  89923. this._standingMatrix.getTranslationToRef(this._workingVector);
  89924. return this._deviceRoomPosition.y + this._workingVector.y;
  89925. }
  89926. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  89927. return this._defaultHeight || 0;
  89928. };
  89929. /**
  89930. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  89931. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  89932. */
  89933. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  89934. var _this = this;
  89935. if (callback === void 0) { callback = function (bool) { }; }
  89936. // Use standing matrix if available
  89937. this.getEngine().initWebVRAsync().then(function (result) {
  89938. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  89939. callback(false);
  89940. }
  89941. else {
  89942. _this._standingMatrix = new BABYLON.Matrix();
  89943. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  89944. if (!_this.getScene().useRightHandedSystem) {
  89945. [2, 6, 8, 9, 14].forEach(function (num) {
  89946. if (_this._standingMatrix) {
  89947. _this._standingMatrix.m[num] *= -1;
  89948. }
  89949. });
  89950. }
  89951. callback(true);
  89952. }
  89953. });
  89954. };
  89955. /**
  89956. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  89957. * @returns A promise with a boolean set to if the standing matrix is supported.
  89958. */
  89959. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  89960. var _this = this;
  89961. return new Promise(function (res, rej) {
  89962. _this.useStandingMatrix(function (supported) {
  89963. res(supported);
  89964. });
  89965. });
  89966. };
  89967. /**
  89968. * Disposes the camera
  89969. */
  89970. WebVRFreeCamera.prototype.dispose = function () {
  89971. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  89972. _super.prototype.dispose.call(this);
  89973. };
  89974. /**
  89975. * Gets a vrController by name.
  89976. * @param name The name of the controller to retreive
  89977. * @returns the controller matching the name specified or null if not found
  89978. */
  89979. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  89980. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  89981. var gp = _a[_i];
  89982. if (gp.hand === name) {
  89983. return gp;
  89984. }
  89985. }
  89986. return null;
  89987. };
  89988. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  89989. /**
  89990. * The controller corrisponding to the users left hand.
  89991. */
  89992. get: function () {
  89993. if (!this._leftController) {
  89994. this._leftController = this.getControllerByName("left");
  89995. }
  89996. return this._leftController;
  89997. },
  89998. enumerable: true,
  89999. configurable: true
  90000. });
  90001. ;
  90002. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  90003. /**
  90004. * The controller corrisponding to the users right hand.
  90005. */
  90006. get: function () {
  90007. if (!this._rightController) {
  90008. this._rightController = this.getControllerByName("right");
  90009. }
  90010. return this._rightController;
  90011. },
  90012. enumerable: true,
  90013. configurable: true
  90014. });
  90015. ;
  90016. /**
  90017. * Casts a ray forward from the vrCamera's gaze.
  90018. * @param length Length of the ray (default: 100)
  90019. * @returns the ray corrisponding to the gaze
  90020. */
  90021. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  90022. if (length === void 0) { length = 100; }
  90023. if (this.leftCamera) {
  90024. // Use left eye to avoid computation to compute center on every call
  90025. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  90026. }
  90027. else {
  90028. return _super.prototype.getForwardRay.call(this, length);
  90029. }
  90030. };
  90031. /**
  90032. * Updates the camera based on device's frame data
  90033. */
  90034. WebVRFreeCamera.prototype._checkInputs = function () {
  90035. if (this._vrDevice && this._vrDevice.isPresenting) {
  90036. this._vrDevice.getFrameData(this._frameData);
  90037. this.updateFromDevice(this._frameData.pose);
  90038. }
  90039. _super.prototype._checkInputs.call(this);
  90040. };
  90041. /**
  90042. * Updates the poseControlled values based on the input device pose.
  90043. * @param poseData Pose coming from the device
  90044. */
  90045. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  90046. if (poseData && poseData.orientation) {
  90047. this.rawPose = poseData;
  90048. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  90049. if (this.getScene().useRightHandedSystem) {
  90050. this._deviceRoomRotationQuaternion.z *= -1;
  90051. this._deviceRoomRotationQuaternion.w *= -1;
  90052. }
  90053. if (this.webVROptions.trackPosition && this.rawPose.position) {
  90054. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  90055. if (this.getScene().useRightHandedSystem) {
  90056. this._deviceRoomPosition.z *= -1;
  90057. }
  90058. }
  90059. }
  90060. };
  90061. /**
  90062. * WebVR's attach control will start broadcasting frames to the device.
  90063. * Note that in certain browsers (chrome for example) this function must be called
  90064. * within a user-interaction callback. Example:
  90065. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  90066. *
  90067. * @param element html element to attach the vrDevice to
  90068. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  90069. */
  90070. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  90071. _super.prototype.attachControl.call(this, element, noPreventDefault);
  90072. this._attached = true;
  90073. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  90074. if (this._vrDevice) {
  90075. this.getEngine().enableVR();
  90076. }
  90077. };
  90078. /**
  90079. * Detaches the camera from the html element and disables VR
  90080. *
  90081. * @param element html element to detach from
  90082. */
  90083. WebVRFreeCamera.prototype.detachControl = function (element) {
  90084. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  90085. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  90086. _super.prototype.detachControl.call(this, element);
  90087. this._attached = false;
  90088. this.getEngine().disableVR();
  90089. };
  90090. /**
  90091. * @returns the name of this class
  90092. */
  90093. WebVRFreeCamera.prototype.getClassName = function () {
  90094. return "WebVRFreeCamera";
  90095. };
  90096. /**
  90097. * Calls resetPose on the vrDisplay
  90098. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  90099. */
  90100. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  90101. //uses the vrDisplay's "resetPose()".
  90102. //pitch and roll won't be affected.
  90103. this._vrDevice.resetPose();
  90104. };
  90105. /**
  90106. * Updates the rig cameras (left and right eye)
  90107. */
  90108. WebVRFreeCamera.prototype._updateRigCameras = function () {
  90109. var camLeft = this._rigCameras[0];
  90110. var camRight = this._rigCameras[1];
  90111. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  90112. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  90113. camLeft.position.copyFrom(this._deviceRoomPosition);
  90114. camRight.position.copyFrom(this._deviceRoomPosition);
  90115. };
  90116. /**
  90117. * Updates the cached values of the camera
  90118. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  90119. */
  90120. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  90121. var _this = this;
  90122. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  90123. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  90124. if (!this.updateCacheCalled) {
  90125. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  90126. this.updateCacheCalled = true;
  90127. this.update();
  90128. }
  90129. // Set working vector to the device position in room space rotated by the new rotation
  90130. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  90131. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  90132. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  90133. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  90134. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  90135. // Add translation from anchor position
  90136. this._deviceToWorld.getTranslationToRef(this._workingVector);
  90137. this._workingVector.addInPlace(this.position);
  90138. this._workingVector.subtractInPlace(this._cache.position);
  90139. this._deviceToWorld.setTranslation(this._workingVector);
  90140. // Set an inverted matrix to be used when updating the camera
  90141. this._deviceToWorld.invertToRef(this._worldToDevice);
  90142. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  90143. this.controllers.forEach(function (controller) {
  90144. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  90145. controller.update();
  90146. });
  90147. }
  90148. if (!ignoreParentClass) {
  90149. _super.prototype._updateCache.call(this);
  90150. }
  90151. this.updateCacheCalled = false;
  90152. };
  90153. /**
  90154. * Updates the current device position and rotation in the babylon world
  90155. */
  90156. WebVRFreeCamera.prototype.update = function () {
  90157. // Get current device position in babylon world
  90158. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  90159. // Get current device rotation in babylon world
  90160. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  90161. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  90162. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  90163. _super.prototype.update.call(this);
  90164. };
  90165. /**
  90166. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  90167. * @returns an identity matrix
  90168. */
  90169. WebVRFreeCamera.prototype._getViewMatrix = function () {
  90170. return BABYLON.Matrix.Identity();
  90171. };
  90172. /**
  90173. * This function is called by the two RIG cameras.
  90174. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  90175. */
  90176. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  90177. var _this = this;
  90178. // Update the parent camera prior to using a child camera to avoid desynchronization
  90179. var parentCamera = this._cameraRigParams["parentCamera"];
  90180. parentCamera._updateCache();
  90181. //WebVR 1.1
  90182. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  90183. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  90184. if (!this.getScene().useRightHandedSystem) {
  90185. [2, 6, 8, 9, 14].forEach(function (num) {
  90186. _this._webvrViewMatrix.m[num] *= -1;
  90187. });
  90188. }
  90189. // update the camera rotation matrix
  90190. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  90191. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  90192. // Computing target and final matrix
  90193. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  90194. // should the view matrix be updated with scale and position offset?
  90195. if (parentCamera.deviceScaleFactor !== 1) {
  90196. this._webvrViewMatrix.invert();
  90197. // scale the position, if set
  90198. if (parentCamera.deviceScaleFactor) {
  90199. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  90200. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  90201. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  90202. }
  90203. this._webvrViewMatrix.invert();
  90204. }
  90205. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  90206. // Compute global position
  90207. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  90208. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  90209. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  90210. this._workingMatrix.getTranslationToRef(this._globalPosition);
  90211. this._markSyncedWithParent();
  90212. return this._webvrViewMatrix;
  90213. };
  90214. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  90215. var _this = this;
  90216. var parentCamera = this.parent;
  90217. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  90218. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  90219. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  90220. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  90221. //babylon compatible matrix
  90222. if (!this.getScene().useRightHandedSystem) {
  90223. [8, 9, 10, 11].forEach(function (num) {
  90224. _this._projectionMatrix.m[num] *= -1;
  90225. });
  90226. }
  90227. return this._projectionMatrix;
  90228. };
  90229. /**
  90230. * Initializes the controllers and their meshes
  90231. */
  90232. WebVRFreeCamera.prototype.initControllers = function () {
  90233. var _this = this;
  90234. this.controllers = [];
  90235. var manager = this.getScene().gamepadManager;
  90236. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  90237. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  90238. var webVrController = gamepad;
  90239. if (webVrController.defaultModel) {
  90240. webVrController.defaultModel.setEnabled(false);
  90241. }
  90242. if (webVrController.hand === "right") {
  90243. _this._rightController = null;
  90244. }
  90245. if (webVrController.hand === "left") {
  90246. _this._leftController = null;
  90247. }
  90248. var controllerIndex = _this.controllers.indexOf(webVrController);
  90249. if (controllerIndex !== -1) {
  90250. _this.controllers.splice(controllerIndex, 1);
  90251. }
  90252. }
  90253. });
  90254. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  90255. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  90256. var webVrController_1 = gamepad;
  90257. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  90258. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  90259. if (_this.webVROptions.controllerMeshes) {
  90260. if (webVrController_1.defaultModel) {
  90261. webVrController_1.defaultModel.setEnabled(true);
  90262. }
  90263. else {
  90264. // Load the meshes
  90265. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  90266. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  90267. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  90268. if (_this.webVROptions.defaultLightingOnControllers) {
  90269. if (!_this._lightOnControllers) {
  90270. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  90271. }
  90272. var activateLightOnSubMeshes_1 = function (mesh, light) {
  90273. var children = mesh.getChildren();
  90274. if (children.length !== 0) {
  90275. children.forEach(function (mesh) {
  90276. light.includedOnlyMeshes.push(mesh);
  90277. activateLightOnSubMeshes_1(mesh, light);
  90278. });
  90279. }
  90280. };
  90281. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  90282. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  90283. }
  90284. });
  90285. }
  90286. }
  90287. webVrController_1.attachToPoseControlledCamera(_this);
  90288. // since this is async - sanity check. Is the controller already stored?
  90289. if (_this.controllers.indexOf(webVrController_1) === -1) {
  90290. //add to the controllers array
  90291. _this.controllers.push(webVrController_1);
  90292. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  90293. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  90294. // So we're overriding setting left & right manually to be sure
  90295. var firstViveWandDetected = false;
  90296. for (var i = 0; i < _this.controllers.length; i++) {
  90297. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  90298. if (!firstViveWandDetected) {
  90299. firstViveWandDetected = true;
  90300. _this.controllers[i].hand = "left";
  90301. }
  90302. else {
  90303. _this.controllers[i].hand = "right";
  90304. }
  90305. }
  90306. }
  90307. //did we find enough controllers? Great! let the developer know.
  90308. if (_this.controllers.length >= 2) {
  90309. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  90310. }
  90311. }
  90312. }
  90313. });
  90314. };
  90315. return WebVRFreeCamera;
  90316. }(BABYLON.FreeCamera));
  90317. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  90318. })(BABYLON || (BABYLON = {}));
  90319. //# sourceMappingURL=babylon.webVRCamera.js.map
  90320. var BABYLON;
  90321. (function (BABYLON) {
  90322. // We're mainly based on the logic defined into the FreeCamera code
  90323. /**
  90324. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  90325. * being tilted forward or back and left or right.
  90326. */
  90327. var DeviceOrientationCamera = /** @class */ (function (_super) {
  90328. __extends(DeviceOrientationCamera, _super);
  90329. /**
  90330. * Creates a new device orientation camera
  90331. * @param name The name of the camera
  90332. * @param position The start position camera
  90333. * @param scene The scene the camera belongs to
  90334. */
  90335. function DeviceOrientationCamera(name, position, scene) {
  90336. var _this = _super.call(this, name, position, scene) || this;
  90337. _this._quaternionCache = new BABYLON.Quaternion();
  90338. _this.inputs.addDeviceOrientation();
  90339. return _this;
  90340. }
  90341. /**
  90342. * Gets the current instance class name ("DeviceOrientationCamera").
  90343. * This helps avoiding instanceof at run time.
  90344. * @returns the class name
  90345. */
  90346. DeviceOrientationCamera.prototype.getClassName = function () {
  90347. return "DeviceOrientationCamera";
  90348. };
  90349. /**
  90350. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  90351. */
  90352. DeviceOrientationCamera.prototype._checkInputs = function () {
  90353. _super.prototype._checkInputs.call(this);
  90354. this._quaternionCache.copyFrom(this.rotationQuaternion);
  90355. if (this._initialQuaternion) {
  90356. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  90357. }
  90358. };
  90359. /**
  90360. * Reset the camera to its default orientation on the specified axis only.
  90361. * @param axis The axis to reset
  90362. */
  90363. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  90364. var _this = this;
  90365. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  90366. //can only work if this camera has a rotation quaternion already.
  90367. if (!this.rotationQuaternion)
  90368. return;
  90369. if (!this._initialQuaternion) {
  90370. this._initialQuaternion = new BABYLON.Quaternion();
  90371. }
  90372. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  90373. ['x', 'y', 'z'].forEach(function (axisName) {
  90374. if (!axis[axisName]) {
  90375. _this._initialQuaternion[axisName] = 0;
  90376. }
  90377. else {
  90378. _this._initialQuaternion[axisName] *= -1;
  90379. }
  90380. });
  90381. this._initialQuaternion.normalize();
  90382. //force rotation update
  90383. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  90384. };
  90385. return DeviceOrientationCamera;
  90386. }(BABYLON.FreeCamera));
  90387. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  90388. })(BABYLON || (BABYLON = {}));
  90389. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  90390. var BABYLON;
  90391. (function (BABYLON) {
  90392. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  90393. __extends(VRDeviceOrientationFreeCamera, _super);
  90394. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  90395. if (compensateDistortion === void 0) { compensateDistortion = true; }
  90396. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  90397. var _this = _super.call(this, name, position, scene) || this;
  90398. vrCameraMetrics.compensateDistortion = compensateDistortion;
  90399. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  90400. return _this;
  90401. }
  90402. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  90403. return "VRDeviceOrientationFreeCamera";
  90404. };
  90405. return VRDeviceOrientationFreeCamera;
  90406. }(BABYLON.DeviceOrientationCamera));
  90407. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  90408. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  90409. __extends(VRDeviceOrientationGamepadCamera, _super);
  90410. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  90411. if (compensateDistortion === void 0) { compensateDistortion = true; }
  90412. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  90413. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  90414. _this.inputs.addGamepad();
  90415. return _this;
  90416. }
  90417. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  90418. return "VRDeviceOrientationGamepadCamera";
  90419. };
  90420. return VRDeviceOrientationGamepadCamera;
  90421. }(VRDeviceOrientationFreeCamera));
  90422. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  90423. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  90424. __extends(VRDeviceOrientationArcRotateCamera, _super);
  90425. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  90426. if (compensateDistortion === void 0) { compensateDistortion = true; }
  90427. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  90428. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  90429. vrCameraMetrics.compensateDistortion = compensateDistortion;
  90430. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  90431. _this.inputs.addVRDeviceOrientation();
  90432. return _this;
  90433. }
  90434. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  90435. return "VRDeviceOrientationArcRotateCamera";
  90436. };
  90437. return VRDeviceOrientationArcRotateCamera;
  90438. }(BABYLON.ArcRotateCamera));
  90439. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  90440. })(BABYLON || (BABYLON = {}));
  90441. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  90442. var BABYLON;
  90443. (function (BABYLON) {
  90444. /**
  90445. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  90446. */
  90447. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  90448. __extends(AnaglyphFreeCamera, _super);
  90449. /**
  90450. * Creates a new AnaglyphFreeCamera
  90451. * @param name defines camera name
  90452. * @param position defines initial position
  90453. * @param interaxialDistance defines distance between each color axis
  90454. * @param scene defines the hosting scene
  90455. */
  90456. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  90457. var _this = _super.call(this, name, position, scene) || this;
  90458. _this.interaxialDistance = interaxialDistance;
  90459. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  90460. return _this;
  90461. }
  90462. /**
  90463. * Gets camera class name
  90464. * @returns AnaglyphFreeCamera
  90465. */
  90466. AnaglyphFreeCamera.prototype.getClassName = function () {
  90467. return "AnaglyphFreeCamera";
  90468. };
  90469. return AnaglyphFreeCamera;
  90470. }(BABYLON.FreeCamera));
  90471. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  90472. /**
  90473. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  90474. */
  90475. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  90476. __extends(AnaglyphArcRotateCamera, _super);
  90477. /**
  90478. * Creates a new AnaglyphArcRotateCamera
  90479. * @param name defines camera name
  90480. * @param alpha defines alpha angle (in radians)
  90481. * @param beta defines beta angle (in radians)
  90482. * @param radius defines radius
  90483. * @param target defines camera target
  90484. * @param interaxialDistance defines distance between each color axis
  90485. * @param scene defines the hosting scene
  90486. */
  90487. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  90488. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  90489. _this.interaxialDistance = interaxialDistance;
  90490. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  90491. return _this;
  90492. }
  90493. /**
  90494. * Gets camera class name
  90495. * @returns AnaglyphArcRotateCamera
  90496. */
  90497. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  90498. return "AnaglyphArcRotateCamera";
  90499. };
  90500. return AnaglyphArcRotateCamera;
  90501. }(BABYLON.ArcRotateCamera));
  90502. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  90503. /**
  90504. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  90505. */
  90506. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  90507. __extends(AnaglyphGamepadCamera, _super);
  90508. /**
  90509. * Creates a new AnaglyphGamepadCamera
  90510. * @param name defines camera name
  90511. * @param position defines initial position
  90512. * @param interaxialDistance defines distance between each color axis
  90513. * @param scene defines the hosting scene
  90514. */
  90515. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  90516. var _this = _super.call(this, name, position, scene) || this;
  90517. _this.interaxialDistance = interaxialDistance;
  90518. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  90519. return _this;
  90520. }
  90521. /**
  90522. * Gets camera class name
  90523. * @returns AnaglyphGamepadCamera
  90524. */
  90525. AnaglyphGamepadCamera.prototype.getClassName = function () {
  90526. return "AnaglyphGamepadCamera";
  90527. };
  90528. return AnaglyphGamepadCamera;
  90529. }(BABYLON.GamepadCamera));
  90530. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  90531. /**
  90532. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  90533. */
  90534. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  90535. __extends(AnaglyphUniversalCamera, _super);
  90536. /**
  90537. * Creates a new AnaglyphUniversalCamera
  90538. * @param name defines camera name
  90539. * @param position defines initial position
  90540. * @param interaxialDistance defines distance between each color axis
  90541. * @param scene defines the hosting scene
  90542. */
  90543. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  90544. var _this = _super.call(this, name, position, scene) || this;
  90545. _this.interaxialDistance = interaxialDistance;
  90546. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  90547. return _this;
  90548. }
  90549. /**
  90550. * Gets camera class name
  90551. * @returns AnaglyphUniversalCamera
  90552. */
  90553. AnaglyphUniversalCamera.prototype.getClassName = function () {
  90554. return "AnaglyphUniversalCamera";
  90555. };
  90556. return AnaglyphUniversalCamera;
  90557. }(BABYLON.UniversalCamera));
  90558. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  90559. /**
  90560. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  90561. */
  90562. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  90563. __extends(StereoscopicFreeCamera, _super);
  90564. /**
  90565. * Creates a new StereoscopicFreeCamera
  90566. * @param name defines camera name
  90567. * @param position defines initial position
  90568. * @param interaxialDistance defines distance between each color axis
  90569. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  90570. * @param scene defines the hosting scene
  90571. */
  90572. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  90573. var _this = _super.call(this, name, position, scene) || this;
  90574. _this.interaxialDistance = interaxialDistance;
  90575. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  90576. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  90577. return _this;
  90578. }
  90579. /**
  90580. * Gets camera class name
  90581. * @returns StereoscopicFreeCamera
  90582. */
  90583. StereoscopicFreeCamera.prototype.getClassName = function () {
  90584. return "StereoscopicFreeCamera";
  90585. };
  90586. return StereoscopicFreeCamera;
  90587. }(BABYLON.FreeCamera));
  90588. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  90589. /**
  90590. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  90591. */
  90592. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  90593. __extends(StereoscopicArcRotateCamera, _super);
  90594. /**
  90595. * Creates a new StereoscopicArcRotateCamera
  90596. * @param name defines camera name
  90597. * @param alpha defines alpha angle (in radians)
  90598. * @param beta defines beta angle (in radians)
  90599. * @param radius defines radius
  90600. * @param target defines camera target
  90601. * @param interaxialDistance defines distance between each color axis
  90602. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  90603. * @param scene defines the hosting scene
  90604. */
  90605. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  90606. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  90607. _this.interaxialDistance = interaxialDistance;
  90608. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  90609. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  90610. return _this;
  90611. }
  90612. /**
  90613. * Gets camera class name
  90614. * @returns StereoscopicArcRotateCamera
  90615. */
  90616. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  90617. return "StereoscopicArcRotateCamera";
  90618. };
  90619. return StereoscopicArcRotateCamera;
  90620. }(BABYLON.ArcRotateCamera));
  90621. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  90622. /**
  90623. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  90624. */
  90625. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  90626. __extends(StereoscopicGamepadCamera, _super);
  90627. /**
  90628. * Creates a new StereoscopicGamepadCamera
  90629. * @param name defines camera name
  90630. * @param position defines initial position
  90631. * @param interaxialDistance defines distance between each color axis
  90632. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  90633. * @param scene defines the hosting scene
  90634. */
  90635. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  90636. var _this = _super.call(this, name, position, scene) || this;
  90637. _this.interaxialDistance = interaxialDistance;
  90638. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  90639. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  90640. return _this;
  90641. }
  90642. /**
  90643. * Gets camera class name
  90644. * @returns StereoscopicGamepadCamera
  90645. */
  90646. StereoscopicGamepadCamera.prototype.getClassName = function () {
  90647. return "StereoscopicGamepadCamera";
  90648. };
  90649. return StereoscopicGamepadCamera;
  90650. }(BABYLON.GamepadCamera));
  90651. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  90652. /**
  90653. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  90654. */
  90655. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  90656. __extends(StereoscopicUniversalCamera, _super);
  90657. /**
  90658. * Creates a new StereoscopicUniversalCamera
  90659. * @param name defines camera name
  90660. * @param position defines initial position
  90661. * @param interaxialDistance defines distance between each color axis
  90662. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  90663. * @param scene defines the hosting scene
  90664. */
  90665. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  90666. var _this = _super.call(this, name, position, scene) || this;
  90667. _this.interaxialDistance = interaxialDistance;
  90668. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  90669. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  90670. return _this;
  90671. }
  90672. /**
  90673. * Gets camera class name
  90674. * @returns StereoscopicUniversalCamera
  90675. */
  90676. StereoscopicUniversalCamera.prototype.getClassName = function () {
  90677. return "StereoscopicUniversalCamera";
  90678. };
  90679. return StereoscopicUniversalCamera;
  90680. }(BABYLON.UniversalCamera));
  90681. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  90682. })(BABYLON || (BABYLON = {}));
  90683. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  90684. var BABYLON;
  90685. (function (BABYLON) {
  90686. var VRExperienceHelperGazer = /** @class */ (function () {
  90687. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  90688. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  90689. this.scene = scene;
  90690. this._pointerDownOnMeshAsked = false;
  90691. this._isActionableMesh = false;
  90692. this._teleportationRequestInitiated = false;
  90693. this._teleportationBackRequestInitiated = false;
  90694. this._rotationRightAsked = false;
  90695. this._rotationLeftAsked = false;
  90696. this._dpadPressed = true;
  90697. this._activePointer = false;
  90698. this._id = VRExperienceHelperGazer._idCounter++;
  90699. // Gaze tracker
  90700. if (!gazeTrackerToClone) {
  90701. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  90702. this._gazeTracker.bakeCurrentTransformIntoVertices();
  90703. this._gazeTracker.isPickable = false;
  90704. this._gazeTracker.isVisible = false;
  90705. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  90706. targetMat.specularColor = BABYLON.Color3.Black();
  90707. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  90708. targetMat.backFaceCulling = false;
  90709. this._gazeTracker.material = targetMat;
  90710. }
  90711. else {
  90712. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  90713. }
  90714. }
  90715. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  90716. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  90717. };
  90718. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  90719. this._pointerDownOnMeshAsked = true;
  90720. if (this._currentHit) {
  90721. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  90722. }
  90723. };
  90724. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  90725. if (this._currentHit) {
  90726. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  90727. }
  90728. this._pointerDownOnMeshAsked = false;
  90729. };
  90730. VRExperienceHelperGazer.prototype._activatePointer = function () {
  90731. this._activePointer = true;
  90732. };
  90733. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  90734. this._activePointer = false;
  90735. };
  90736. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  90737. if (distance === void 0) { distance = 100; }
  90738. };
  90739. VRExperienceHelperGazer.prototype.dispose = function () {
  90740. this._interactionsEnabled = false;
  90741. this._teleportationEnabled = false;
  90742. if (this._gazeTracker) {
  90743. this._gazeTracker.dispose();
  90744. }
  90745. };
  90746. VRExperienceHelperGazer._idCounter = 0;
  90747. return VRExperienceHelperGazer;
  90748. }());
  90749. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  90750. __extends(VRExperienceHelperControllerGazer, _super);
  90751. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  90752. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  90753. _this.webVRController = webVRController;
  90754. // Laser pointer
  90755. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  90756. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  90757. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  90758. laserPointerMaterial.alpha = 0.6;
  90759. _this._laserPointer.material = laserPointerMaterial;
  90760. _this._laserPointer.rotation.x = Math.PI / 2;
  90761. _this._laserPointer.position.z = -0.5;
  90762. _this._laserPointer.isVisible = false;
  90763. _this._laserPointer.isPickable = false;
  90764. if (!webVRController.mesh) {
  90765. // Create an empty mesh that is used prior to loading the high quality model
  90766. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  90767. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  90768. preloadPointerPose.rotation.x = -0.7;
  90769. preloadMesh.addChild(preloadPointerPose);
  90770. webVRController.attachToMesh(preloadMesh);
  90771. }
  90772. _this._setLaserPointerParent(webVRController.mesh);
  90773. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  90774. _this._setLaserPointerParent(mesh);
  90775. });
  90776. return _this;
  90777. }
  90778. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  90779. return this.webVRController.getForwardRay(length);
  90780. };
  90781. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  90782. _super.prototype._activatePointer.call(this);
  90783. this._laserPointer.isVisible = true;
  90784. };
  90785. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  90786. _super.prototype._deactivatePointer.call(this);
  90787. this._laserPointer.isVisible = false;
  90788. };
  90789. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  90790. this._laserPointer.material.emissiveColor = color;
  90791. };
  90792. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  90793. var makeNotPick = function (root) {
  90794. root.name += " laserPointer";
  90795. root.isPickable = false;
  90796. root.getChildMeshes().forEach(function (c) {
  90797. makeNotPick(c);
  90798. });
  90799. };
  90800. makeNotPick(mesh);
  90801. var childMeshes = mesh.getChildMeshes();
  90802. this.webVRController._pointingPoseNode = null;
  90803. for (var i = 0; i < childMeshes.length; i++) {
  90804. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  90805. mesh = childMeshes[i];
  90806. this.webVRController._pointingPoseNode = mesh;
  90807. break;
  90808. }
  90809. }
  90810. this._laserPointer.parent = mesh;
  90811. };
  90812. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  90813. if (distance === void 0) { distance = 100; }
  90814. this._laserPointer.scaling.y = distance;
  90815. this._laserPointer.position.z = -distance / 2;
  90816. };
  90817. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  90818. _super.prototype.dispose.call(this);
  90819. this._laserPointer.dispose();
  90820. if (this._meshAttachedObserver) {
  90821. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  90822. }
  90823. };
  90824. return VRExperienceHelperControllerGazer;
  90825. }(VRExperienceHelperGazer));
  90826. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  90827. __extends(VRExperienceHelperCameraGazer, _super);
  90828. function VRExperienceHelperCameraGazer(getCamera, scene) {
  90829. var _this = _super.call(this, scene) || this;
  90830. _this.getCamera = getCamera;
  90831. return _this;
  90832. }
  90833. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  90834. var camera = this.getCamera();
  90835. if (camera) {
  90836. return camera.getForwardRay(length);
  90837. }
  90838. else {
  90839. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  90840. }
  90841. };
  90842. return VRExperienceHelperCameraGazer;
  90843. }(VRExperienceHelperGazer));
  90844. /**
  90845. * Helps to quickly add VR support to an existing scene.
  90846. * See http://doc.babylonjs.com/how_to/webvr_helper
  90847. */
  90848. var VRExperienceHelper = /** @class */ (function () {
  90849. /**
  90850. * Instantiates a VRExperienceHelper.
  90851. * Helps to quickly add VR support to an existing scene.
  90852. * @param scene The scene the VRExperienceHelper belongs to.
  90853. * @param webVROptions Options to modify the vr experience helper's behavior.
  90854. */
  90855. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  90856. if (webVROptions === void 0) { webVROptions = {}; }
  90857. var _this = this;
  90858. this.webVROptions = webVROptions;
  90859. // Can the system support WebVR, even if a headset isn't plugged in?
  90860. this._webVRsupported = false;
  90861. // If WebVR is supported, is a headset plugged in and are we ready to present?
  90862. this._webVRready = false;
  90863. // Are we waiting for the requestPresent callback to complete?
  90864. this._webVRrequesting = false;
  90865. // Are we presenting to the headset right now?
  90866. this._webVRpresenting = false;
  90867. // Are we presenting in the fullscreen fallback?
  90868. this._fullscreenVRpresenting = false;
  90869. /**
  90870. * Observable raised when entering VR.
  90871. */
  90872. this.onEnteringVRObservable = new BABYLON.Observable();
  90873. /**
  90874. * Observable raised when exiting VR.
  90875. */
  90876. this.onExitingVRObservable = new BABYLON.Observable();
  90877. /**
  90878. * Observable raised when controller mesh is loaded.
  90879. */
  90880. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  90881. this._useCustomVRButton = false;
  90882. this._teleportationRequested = false;
  90883. this._teleportActive = false;
  90884. this._floorMeshesCollection = [];
  90885. this._rotationAllowed = true;
  90886. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  90887. this._isDefaultTeleportationTarget = true;
  90888. this._teleportationFillColor = "#444444";
  90889. this._teleportationBorderColor = "#FFFFFF";
  90890. this._rotationAngle = 0;
  90891. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  90892. this._padSensibilityUp = 0.65;
  90893. this._padSensibilityDown = 0.35;
  90894. this.leftController = null;
  90895. this.rightController = null;
  90896. /**
  90897. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  90898. */
  90899. this.onNewMeshSelected = new BABYLON.Observable();
  90900. /**
  90901. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  90902. */
  90903. this.onNewMeshPicked = new BABYLON.Observable();
  90904. /**
  90905. * Observable raised before camera teleportation
  90906. */
  90907. this.onBeforeCameraTeleport = new BABYLON.Observable();
  90908. /**
  90909. * Observable raised after camera teleportation
  90910. */
  90911. this.onAfterCameraTeleport = new BABYLON.Observable();
  90912. /**
  90913. * Observable raised when current selected mesh gets unselected
  90914. */
  90915. this.onSelectedMeshUnselected = new BABYLON.Observable();
  90916. /**
  90917. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  90918. */
  90919. this.teleportationEnabled = true;
  90920. this._teleportationInitialized = false;
  90921. this._interactionsEnabled = false;
  90922. this._interactionsRequested = false;
  90923. this._displayGaze = true;
  90924. this._displayLaserPointer = true;
  90925. this._onResize = function () {
  90926. _this.moveButtonToBottomRight();
  90927. if (_this._fullscreenVRpresenting && _this._webVRready) {
  90928. _this.exitVR();
  90929. }
  90930. };
  90931. this._onFullscreenChange = function () {
  90932. if (document.fullscreen !== undefined) {
  90933. _this._fullscreenVRpresenting = document.fullscreen;
  90934. }
  90935. else if (document.mozFullScreen !== undefined) {
  90936. _this._fullscreenVRpresenting = document.mozFullScreen;
  90937. }
  90938. else if (document.webkitIsFullScreen !== undefined) {
  90939. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  90940. }
  90941. else if (document.msIsFullScreen !== undefined) {
  90942. _this._fullscreenVRpresenting = document.msIsFullScreen;
  90943. }
  90944. if (!_this._fullscreenVRpresenting && _this._canvas) {
  90945. _this.exitVR();
  90946. if (!_this._useCustomVRButton) {
  90947. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  90948. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  90949. }
  90950. }
  90951. };
  90952. this.beforeRender = function () {
  90953. if (_this.leftController && _this.leftController._activePointer) {
  90954. _this._castRayAndSelectObject(_this.leftController);
  90955. }
  90956. if (_this.rightController && _this.rightController._activePointer) {
  90957. _this._castRayAndSelectObject(_this.rightController);
  90958. }
  90959. if (_this._noControllerIsActive) {
  90960. _this._castRayAndSelectObject(_this._cameraGazer);
  90961. }
  90962. else {
  90963. _this._cameraGazer._gazeTracker.isVisible = false;
  90964. }
  90965. };
  90966. this._onNewGamepadConnected = function (gamepad) {
  90967. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  90968. if (gamepad.leftStick) {
  90969. gamepad.onleftstickchanged(function (stickValues) {
  90970. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  90971. // Listening to classic/xbox gamepad only if no VR controller is active
  90972. if ((!_this.leftController && !_this.rightController) ||
  90973. ((_this.leftController && !_this.leftController._activePointer) &&
  90974. (_this.rightController && !_this.rightController._activePointer))) {
  90975. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  90976. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  90977. }
  90978. }
  90979. });
  90980. }
  90981. if (gamepad.rightStick) {
  90982. gamepad.onrightstickchanged(function (stickValues) {
  90983. if (_this._teleportationInitialized) {
  90984. _this._checkRotate(stickValues, _this._cameraGazer);
  90985. }
  90986. });
  90987. }
  90988. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  90989. gamepad.onbuttondown(function (buttonPressed) {
  90990. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  90991. _this._cameraGazer._selectionPointerDown();
  90992. }
  90993. });
  90994. gamepad.onbuttonup(function (buttonPressed) {
  90995. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  90996. _this._cameraGazer._selectionPointerUp();
  90997. }
  90998. });
  90999. }
  91000. }
  91001. else {
  91002. var webVRController = gamepad;
  91003. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  91004. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  91005. _this.rightController = controller;
  91006. }
  91007. else {
  91008. _this.leftController = controller;
  91009. }
  91010. _this._tryEnableInteractionOnController(controller);
  91011. }
  91012. };
  91013. // 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
  91014. this._tryEnableInteractionOnController = function (controller) {
  91015. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  91016. _this._enableInteractionOnController(controller);
  91017. }
  91018. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  91019. _this._enableTeleportationOnController(controller);
  91020. }
  91021. };
  91022. this._onNewGamepadDisconnected = function (gamepad) {
  91023. if (gamepad instanceof BABYLON.WebVRController) {
  91024. if (gamepad.hand === "left" && _this.leftController != null) {
  91025. _this.leftController.dispose();
  91026. _this.leftController = null;
  91027. }
  91028. if (gamepad.hand === "right" && _this.rightController != null) {
  91029. _this.rightController.dispose();
  91030. _this.rightController = null;
  91031. }
  91032. }
  91033. };
  91034. this._workingVector = BABYLON.Vector3.Zero();
  91035. this._workingQuaternion = BABYLON.Quaternion.Identity();
  91036. this._workingMatrix = BABYLON.Matrix.Identity();
  91037. this._scene = scene;
  91038. this._canvas = scene.getEngine().getRenderingCanvas();
  91039. // Parse options
  91040. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  91041. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  91042. }
  91043. if (webVROptions.createDeviceOrientationCamera === undefined) {
  91044. webVROptions.createDeviceOrientationCamera = true;
  91045. }
  91046. if (webVROptions.laserToggle === undefined) {
  91047. webVROptions.laserToggle = true;
  91048. }
  91049. if (webVROptions.defaultHeight === undefined) {
  91050. webVROptions.defaultHeight = 1.7;
  91051. }
  91052. if (webVROptions.useCustomVRButton) {
  91053. this._useCustomVRButton = true;
  91054. if (webVROptions.customVRButton) {
  91055. this._btnVR = webVROptions.customVRButton;
  91056. }
  91057. }
  91058. if (webVROptions.rayLength) {
  91059. this._rayLength = webVROptions.rayLength;
  91060. }
  91061. this._defaultHeight = webVROptions.defaultHeight;
  91062. if (webVROptions.positionScale) {
  91063. this._rayLength *= webVROptions.positionScale;
  91064. this._defaultHeight *= webVROptions.positionScale;
  91065. }
  91066. // Set position
  91067. if (this._scene.activeCamera) {
  91068. this._position = this._scene.activeCamera.position.clone();
  91069. }
  91070. else {
  91071. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  91072. }
  91073. // Set non-vr camera
  91074. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  91075. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  91076. // Copy data from existing camera
  91077. if (this._scene.activeCamera) {
  91078. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  91079. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  91080. // Set rotation from previous camera
  91081. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  91082. var targetCamera = this._scene.activeCamera;
  91083. if (targetCamera.rotationQuaternion) {
  91084. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  91085. }
  91086. else {
  91087. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  91088. }
  91089. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  91090. }
  91091. }
  91092. this._scene.activeCamera = this._deviceOrientationCamera;
  91093. if (this._canvas) {
  91094. this._scene.activeCamera.attachControl(this._canvas);
  91095. }
  91096. }
  91097. else {
  91098. this._existingCamera = this._scene.activeCamera;
  91099. }
  91100. // Create VR cameras
  91101. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  91102. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  91103. }
  91104. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  91105. this._webVRCamera.useStandingMatrix();
  91106. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  91107. // Create default button
  91108. if (!this._useCustomVRButton) {
  91109. this._btnVR = document.createElement("BUTTON");
  91110. this._btnVR.className = "babylonVRicon";
  91111. this._btnVR.id = "babylonVRiconbtn";
  91112. this._btnVR.title = "Click to switch to VR";
  91113. 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) }";
  91114. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  91115. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  91116. // css += ".babylonVRicon.vrdisplaysupported { }";
  91117. // css += ".babylonVRicon.vrdisplayready { }";
  91118. // css += ".babylonVRicon.vrdisplayrequesting { }";
  91119. var style = document.createElement('style');
  91120. style.appendChild(document.createTextNode(css));
  91121. document.getElementsByTagName('head')[0].appendChild(style);
  91122. this.moveButtonToBottomRight();
  91123. }
  91124. // VR button click event
  91125. if (this._btnVR) {
  91126. this._btnVR.addEventListener("click", function () {
  91127. if (!_this.isInVRMode) {
  91128. _this.enterVR();
  91129. }
  91130. else {
  91131. _this.exitVR();
  91132. }
  91133. });
  91134. }
  91135. // Window events
  91136. window.addEventListener("resize", this._onResize);
  91137. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  91138. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  91139. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  91140. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  91141. // Display vr button when headset is connected
  91142. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  91143. this.displayVRButton();
  91144. }
  91145. else {
  91146. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  91147. if (e.vrDisplay) {
  91148. _this.displayVRButton();
  91149. }
  91150. });
  91151. }
  91152. // Exiting VR mode using 'ESC' key on desktop
  91153. this._onKeyDown = function (event) {
  91154. if (event.keyCode === 27 && _this.isInVRMode) {
  91155. _this.exitVR();
  91156. }
  91157. };
  91158. document.addEventListener("keydown", this._onKeyDown);
  91159. // Exiting VR mode double tapping the touch screen
  91160. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  91161. if (_this.isInVRMode) {
  91162. _this.exitVR();
  91163. if (_this._fullscreenVRpresenting) {
  91164. _this._scene.getEngine().switchFullscreen(true);
  91165. }
  91166. }
  91167. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  91168. // Listen for WebVR display changes
  91169. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  91170. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  91171. this._onVRRequestPresentStart = function () {
  91172. _this._webVRrequesting = true;
  91173. _this.updateButtonVisibility();
  91174. };
  91175. this._onVRRequestPresentComplete = function (success) {
  91176. _this._webVRrequesting = false;
  91177. _this.updateButtonVisibility();
  91178. };
  91179. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  91180. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  91181. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  91182. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  91183. scene.onDisposeObservable.add(function () {
  91184. _this.dispose();
  91185. });
  91186. // Gamepad connection events
  91187. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  91188. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  91189. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  91190. this.updateButtonVisibility();
  91191. //create easing functions
  91192. this._circleEase = new BABYLON.CircleEase();
  91193. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  91194. if (this.webVROptions.floorMeshes) {
  91195. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  91196. }
  91197. }
  91198. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  91199. /** Return this.onEnteringVRObservable
  91200. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  91201. */
  91202. get: function () {
  91203. return this.onEnteringVRObservable;
  91204. },
  91205. enumerable: true,
  91206. configurable: true
  91207. });
  91208. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  91209. /** Return this.onExitingVRObservable
  91210. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  91211. */
  91212. get: function () {
  91213. return this.onExitingVRObservable;
  91214. },
  91215. enumerable: true,
  91216. configurable: true
  91217. });
  91218. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  91219. /** Return this.onControllerMeshLoadedObservable
  91220. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  91221. */
  91222. get: function () {
  91223. return this.onControllerMeshLoadedObservable;
  91224. },
  91225. enumerable: true,
  91226. configurable: true
  91227. });
  91228. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  91229. /**
  91230. * The mesh used to display where the user is going to teleport.
  91231. */
  91232. get: function () {
  91233. return this._teleportationTarget;
  91234. },
  91235. /**
  91236. * Sets the mesh to be used to display where the user is going to teleport.
  91237. */
  91238. set: function (value) {
  91239. if (value) {
  91240. value.name = "teleportationTarget";
  91241. this._isDefaultTeleportationTarget = false;
  91242. this._teleportationTarget = value;
  91243. }
  91244. },
  91245. enumerable: true,
  91246. configurable: true
  91247. });
  91248. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  91249. /**
  91250. * The mesh used to display where the user is selecting,
  91251. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  91252. * See http://doc.babylonjs.com/resources/baking_transformations
  91253. */
  91254. get: function () {
  91255. return this._cameraGazer._gazeTracker;
  91256. },
  91257. set: function (value) {
  91258. if (value) {
  91259. this._cameraGazer._gazeTracker = value;
  91260. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  91261. this._cameraGazer._gazeTracker.isPickable = false;
  91262. this._cameraGazer._gazeTracker.isVisible = false;
  91263. this._cameraGazer._gazeTracker.name = "gazeTracker";
  91264. if (this.leftController) {
  91265. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  91266. }
  91267. if (this.rightController) {
  91268. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  91269. }
  91270. }
  91271. },
  91272. enumerable: true,
  91273. configurable: true
  91274. });
  91275. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  91276. /**
  91277. * If the ray of the gaze should be displayed.
  91278. */
  91279. get: function () {
  91280. return this._displayGaze;
  91281. },
  91282. /**
  91283. * Sets if the ray of the gaze should be displayed.
  91284. */
  91285. set: function (value) {
  91286. this._displayGaze = value;
  91287. if (!value) {
  91288. this._cameraGazer._gazeTracker.isVisible = false;
  91289. if (this.leftController) {
  91290. this.leftController._gazeTracker.isVisible = false;
  91291. }
  91292. if (this.rightController) {
  91293. this.rightController._gazeTracker.isVisible = false;
  91294. }
  91295. }
  91296. },
  91297. enumerable: true,
  91298. configurable: true
  91299. });
  91300. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  91301. /**
  91302. * If the ray of the LaserPointer should be displayed.
  91303. */
  91304. get: function () {
  91305. return this._displayLaserPointer;
  91306. },
  91307. /**
  91308. * Sets if the ray of the LaserPointer should be displayed.
  91309. */
  91310. set: function (value) {
  91311. this._displayLaserPointer = value;
  91312. if (!value) {
  91313. if (this.rightController) {
  91314. this.rightController._deactivatePointer();
  91315. this.rightController._gazeTracker.isVisible = false;
  91316. }
  91317. if (this.leftController) {
  91318. this.leftController._deactivatePointer();
  91319. this.leftController._gazeTracker.isVisible = false;
  91320. }
  91321. }
  91322. else {
  91323. if (this.rightController) {
  91324. this.rightController._activatePointer();
  91325. }
  91326. if (this.leftController) {
  91327. this.leftController._activatePointer();
  91328. }
  91329. }
  91330. },
  91331. enumerable: true,
  91332. configurable: true
  91333. });
  91334. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  91335. /**
  91336. * The deviceOrientationCamera used as the camera when not in VR.
  91337. */
  91338. get: function () {
  91339. return this._deviceOrientationCamera;
  91340. },
  91341. enumerable: true,
  91342. configurable: true
  91343. });
  91344. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  91345. /**
  91346. * Based on the current WebVR support, returns the current VR camera used.
  91347. */
  91348. get: function () {
  91349. if (this._webVRready) {
  91350. return this._webVRCamera;
  91351. }
  91352. else {
  91353. return this._scene.activeCamera;
  91354. }
  91355. },
  91356. enumerable: true,
  91357. configurable: true
  91358. });
  91359. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  91360. /**
  91361. * The webVRCamera which is used when in VR.
  91362. */
  91363. get: function () {
  91364. return this._webVRCamera;
  91365. },
  91366. enumerable: true,
  91367. configurable: true
  91368. });
  91369. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  91370. /**
  91371. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  91372. */
  91373. get: function () {
  91374. return this._vrDeviceOrientationCamera;
  91375. },
  91376. enumerable: true,
  91377. configurable: true
  91378. });
  91379. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  91380. get: function () {
  91381. var result = this._cameraGazer._teleportationRequestInitiated
  91382. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  91383. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  91384. return result;
  91385. },
  91386. enumerable: true,
  91387. configurable: true
  91388. });
  91389. // Raised when one of the controller has loaded successfully its associated default mesh
  91390. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  91391. if (this.leftController && this.leftController.webVRController == webVRController) {
  91392. if (webVRController.mesh) {
  91393. this.leftController._setLaserPointerParent(webVRController.mesh);
  91394. }
  91395. }
  91396. if (this.rightController && this.rightController.webVRController == webVRController) {
  91397. if (webVRController.mesh) {
  91398. this.rightController._setLaserPointerParent(webVRController.mesh);
  91399. }
  91400. }
  91401. try {
  91402. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  91403. }
  91404. catch (err) {
  91405. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  91406. }
  91407. };
  91408. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  91409. /**
  91410. * Gets a value indicating if we are currently in VR mode.
  91411. */
  91412. get: function () {
  91413. return this._webVRpresenting || this._fullscreenVRpresenting;
  91414. },
  91415. enumerable: true,
  91416. configurable: true
  91417. });
  91418. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  91419. var vrDisplay = this._scene.getEngine().getVRDevice();
  91420. if (vrDisplay) {
  91421. var wasPresenting = this._webVRpresenting;
  91422. // A VR display is connected
  91423. this._webVRpresenting = vrDisplay.isPresenting;
  91424. if (wasPresenting && !this._webVRpresenting)
  91425. this.exitVR();
  91426. }
  91427. else {
  91428. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  91429. }
  91430. this.updateButtonVisibility();
  91431. };
  91432. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  91433. this._webVRsupported = eventArgs.vrSupported;
  91434. this._webVRready = !!eventArgs.vrDisplay;
  91435. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  91436. this.updateButtonVisibility();
  91437. };
  91438. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  91439. if (this._canvas && !this._useCustomVRButton) {
  91440. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  91441. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  91442. }
  91443. };
  91444. VRExperienceHelper.prototype.displayVRButton = function () {
  91445. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  91446. document.body.appendChild(this._btnVR);
  91447. this._btnVRDisplayed = true;
  91448. }
  91449. };
  91450. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  91451. if (!this._btnVR || this._useCustomVRButton) {
  91452. return;
  91453. }
  91454. this._btnVR.className = "babylonVRicon";
  91455. if (this.isInVRMode) {
  91456. this._btnVR.className += " vrdisplaypresenting";
  91457. }
  91458. else {
  91459. if (this._webVRready)
  91460. this._btnVR.className += " vrdisplayready";
  91461. if (this._webVRsupported)
  91462. this._btnVR.className += " vrdisplaysupported";
  91463. if (this._webVRrequesting)
  91464. this._btnVR.className += " vrdisplayrequesting";
  91465. }
  91466. };
  91467. /**
  91468. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  91469. * Otherwise, will use the fullscreen API.
  91470. */
  91471. VRExperienceHelper.prototype.enterVR = function () {
  91472. if (this.onEnteringVRObservable) {
  91473. try {
  91474. this.onEnteringVRObservable.notifyObservers(this);
  91475. }
  91476. catch (err) {
  91477. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  91478. }
  91479. }
  91480. if (this._scene.activeCamera) {
  91481. this._position = this._scene.activeCamera.position.clone();
  91482. // make sure that we return to the last active camera
  91483. this._existingCamera = this._scene.activeCamera;
  91484. }
  91485. if (this._webVRrequesting)
  91486. return;
  91487. // If WebVR is supported and a headset is connected
  91488. if (this._webVRready) {
  91489. if (!this._webVRpresenting) {
  91490. this._webVRCamera.position = this._position;
  91491. this._scene.activeCamera = this._webVRCamera;
  91492. }
  91493. }
  91494. else if (this._vrDeviceOrientationCamera) {
  91495. this._vrDeviceOrientationCamera.position = this._position;
  91496. if (this._scene.activeCamera) {
  91497. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  91498. }
  91499. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  91500. this._scene.getEngine().switchFullscreen(true);
  91501. this.updateButtonVisibility();
  91502. }
  91503. if (this._scene.activeCamera && this._canvas) {
  91504. this._scene.activeCamera.attachControl(this._canvas);
  91505. }
  91506. if (this._interactionsEnabled) {
  91507. this._scene.registerBeforeRender(this.beforeRender);
  91508. }
  91509. };
  91510. /**
  91511. * Attempt to exit VR, or fullscreen.
  91512. */
  91513. VRExperienceHelper.prototype.exitVR = function () {
  91514. if (this.onExitingVRObservable) {
  91515. try {
  91516. this.onExitingVRObservable.notifyObservers(this);
  91517. }
  91518. catch (err) {
  91519. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  91520. }
  91521. }
  91522. if (this._webVRpresenting) {
  91523. this._scene.getEngine().disableVR();
  91524. }
  91525. if (this._scene.activeCamera) {
  91526. this._position = this._scene.activeCamera.position.clone();
  91527. }
  91528. if (this._deviceOrientationCamera) {
  91529. this._deviceOrientationCamera.position = this._position;
  91530. this._scene.activeCamera = this._deviceOrientationCamera;
  91531. if (this._canvas) {
  91532. this._scene.activeCamera.attachControl(this._canvas);
  91533. }
  91534. }
  91535. else if (this._existingCamera) {
  91536. this._existingCamera.position = this._position;
  91537. this._scene.activeCamera = this._existingCamera;
  91538. }
  91539. this.updateButtonVisibility();
  91540. if (this._interactionsEnabled) {
  91541. this._scene.unregisterBeforeRender(this.beforeRender);
  91542. }
  91543. // resize to update width and height when exiting vr exits fullscreen
  91544. this._scene.getEngine().resize();
  91545. };
  91546. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  91547. /**
  91548. * The position of the vr experience helper.
  91549. */
  91550. get: function () {
  91551. return this._position;
  91552. },
  91553. /**
  91554. * Sets the position of the vr experience helper.
  91555. */
  91556. set: function (value) {
  91557. this._position = value;
  91558. if (this._scene.activeCamera) {
  91559. this._scene.activeCamera.position = value;
  91560. }
  91561. },
  91562. enumerable: true,
  91563. configurable: true
  91564. });
  91565. /**
  91566. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  91567. */
  91568. VRExperienceHelper.prototype.enableInteractions = function () {
  91569. var _this = this;
  91570. if (!this._interactionsEnabled) {
  91571. this._interactionsRequested = true;
  91572. if (this.leftController) {
  91573. this._enableInteractionOnController(this.leftController);
  91574. }
  91575. if (this.rightController) {
  91576. this._enableInteractionOnController(this.rightController);
  91577. }
  91578. this.raySelectionPredicate = function (mesh) {
  91579. return mesh.isVisible;
  91580. };
  91581. this.meshSelectionPredicate = function (mesh) {
  91582. return true;
  91583. };
  91584. this._raySelectionPredicate = function (mesh) {
  91585. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  91586. && mesh.name.indexOf("teleportationTarget") === -1
  91587. && mesh.name.indexOf("torusTeleportation") === -1
  91588. && mesh.name.indexOf("laserPointer") === -1)) {
  91589. return _this.raySelectionPredicate(mesh);
  91590. }
  91591. return false;
  91592. };
  91593. this._interactionsEnabled = true;
  91594. }
  91595. };
  91596. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  91597. get: function () {
  91598. return !(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer);
  91599. },
  91600. enumerable: true,
  91601. configurable: true
  91602. });
  91603. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  91604. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  91605. if (this._floorMeshesCollection[i].id === mesh.id) {
  91606. return true;
  91607. }
  91608. }
  91609. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  91610. return true;
  91611. }
  91612. return false;
  91613. };
  91614. /**
  91615. * Adds a floor mesh to be used for teleportation.
  91616. * @param floorMesh the mesh to be used for teleportation.
  91617. */
  91618. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  91619. if (!this._floorMeshesCollection) {
  91620. return;
  91621. }
  91622. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  91623. return;
  91624. }
  91625. this._floorMeshesCollection.push(floorMesh);
  91626. };
  91627. /**
  91628. * Removes a floor mesh from being used for teleportation.
  91629. * @param floorMesh the mesh to be removed.
  91630. */
  91631. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  91632. if (!this._floorMeshesCollection) {
  91633. return;
  91634. }
  91635. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  91636. if (meshIndex !== -1) {
  91637. this._floorMeshesCollection.splice(meshIndex, 1);
  91638. }
  91639. };
  91640. /**
  91641. * Enables interactions and teleportation using the VR controllers and gaze.
  91642. * @param vrTeleportationOptions options to modify teleportation behavior.
  91643. */
  91644. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  91645. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  91646. if (!this._teleportationInitialized) {
  91647. this._teleportationRequested = true;
  91648. this.enableInteractions();
  91649. if (vrTeleportationOptions.floorMeshName) {
  91650. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  91651. }
  91652. if (vrTeleportationOptions.floorMeshes) {
  91653. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  91654. }
  91655. if (this.leftController != null) {
  91656. this._enableTeleportationOnController(this.leftController);
  91657. }
  91658. if (this.rightController != null) {
  91659. this._enableTeleportationOnController(this.rightController);
  91660. }
  91661. // Creates an image processing post process for the vignette not relying
  91662. // on the main scene configuration for image processing to reduce setup and spaces
  91663. // (gamma/linear) conflicts.
  91664. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  91665. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  91666. imageProcessingConfiguration.vignetteEnabled = true;
  91667. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  91668. this._webVRCamera.detachPostProcess(this._postProcessMove);
  91669. this._teleportationInitialized = true;
  91670. if (this._isDefaultTeleportationTarget) {
  91671. this._createTeleportationCircles();
  91672. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  91673. }
  91674. }
  91675. };
  91676. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  91677. var _this = this;
  91678. var controllerMesh = controller.webVRController.mesh;
  91679. if (controllerMesh) {
  91680. controller._interactionsEnabled = true;
  91681. controller._activatePointer();
  91682. if (this.webVROptions.laserToggle) {
  91683. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  91684. // Enabling / disabling laserPointer
  91685. if (_this._displayLaserPointer && stateObject.value === 1) {
  91686. if (controller._activePointer) {
  91687. controller._deactivatePointer();
  91688. }
  91689. else {
  91690. controller._activatePointer();
  91691. }
  91692. if (_this.displayGaze) {
  91693. controller._gazeTracker.isVisible = controller._activePointer;
  91694. }
  91695. }
  91696. });
  91697. }
  91698. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  91699. var gazer = controller;
  91700. if (_this._noControllerIsActive) {
  91701. gazer = _this._cameraGazer;
  91702. }
  91703. if (!gazer._pointerDownOnMeshAsked) {
  91704. if (stateObject.value > _this._padSensibilityUp) {
  91705. gazer._selectionPointerDown();
  91706. }
  91707. }
  91708. else if (stateObject.value < _this._padSensibilityDown) {
  91709. gazer._selectionPointerUp();
  91710. }
  91711. });
  91712. }
  91713. };
  91714. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  91715. // Dont teleport if another gaze already requested teleportation
  91716. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  91717. return;
  91718. }
  91719. if (!gazer._teleportationRequestInitiated) {
  91720. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  91721. gazer._activatePointer();
  91722. gazer._teleportationRequestInitiated = true;
  91723. }
  91724. }
  91725. else {
  91726. // Listening to the proper controller values changes to confirm teleportation
  91727. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  91728. if (this._teleportActive) {
  91729. this._teleportCamera(this._haloCenter);
  91730. }
  91731. gazer._teleportationRequestInitiated = false;
  91732. }
  91733. }
  91734. };
  91735. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  91736. // Only rotate when user is not currently selecting a teleportation location
  91737. if (gazer._teleportationRequestInitiated) {
  91738. return;
  91739. }
  91740. if (!gazer._rotationLeftAsked) {
  91741. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  91742. gazer._rotationLeftAsked = true;
  91743. if (this._rotationAllowed) {
  91744. this._rotateCamera(false);
  91745. }
  91746. }
  91747. }
  91748. else {
  91749. if (stateObject.x > -this._padSensibilityDown) {
  91750. gazer._rotationLeftAsked = false;
  91751. }
  91752. }
  91753. if (!gazer._rotationRightAsked) {
  91754. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  91755. gazer._rotationRightAsked = true;
  91756. if (this._rotationAllowed) {
  91757. this._rotateCamera(true);
  91758. }
  91759. }
  91760. }
  91761. else {
  91762. if (stateObject.x < this._padSensibilityDown) {
  91763. gazer._rotationRightAsked = false;
  91764. }
  91765. }
  91766. };
  91767. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  91768. // Only teleport backwards when user is not currently selecting a teleportation location
  91769. if (gazer._teleportationRequestInitiated) {
  91770. return;
  91771. }
  91772. // Teleport backwards
  91773. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  91774. if (!gazer._teleportationBackRequestInitiated) {
  91775. if (!this.currentVRCamera) {
  91776. return;
  91777. }
  91778. // Get rotation and position of the current camera
  91779. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  91780. var position = this.currentVRCamera.position;
  91781. // If the camera has device position, use that instead
  91782. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  91783. rotation = this.currentVRCamera.deviceRotationQuaternion;
  91784. position = this.currentVRCamera.devicePosition;
  91785. }
  91786. // Get matrix with only the y rotation of the device rotation
  91787. rotation.toEulerAnglesToRef(this._workingVector);
  91788. this._workingVector.z = 0;
  91789. this._workingVector.x = 0;
  91790. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  91791. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  91792. // Rotate backwards ray by device rotation to cast at the ground behind the user
  91793. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  91794. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  91795. var ray = new BABYLON.Ray(position, this._workingVector);
  91796. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  91797. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  91798. this._teleportCamera(hit.pickedPoint);
  91799. }
  91800. gazer._teleportationBackRequestInitiated = true;
  91801. }
  91802. }
  91803. else {
  91804. gazer._teleportationBackRequestInitiated = false;
  91805. }
  91806. };
  91807. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  91808. var _this = this;
  91809. var controllerMesh = controller.webVRController.mesh;
  91810. if (controllerMesh) {
  91811. if (!controller._interactionsEnabled) {
  91812. this._enableInteractionOnController(controller);
  91813. }
  91814. controller._interactionsEnabled = true;
  91815. controller._teleportationEnabled = true;
  91816. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  91817. controller._dpadPressed = false;
  91818. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  91819. controller._dpadPressed = stateObject.pressed;
  91820. if (!controller._dpadPressed) {
  91821. controller._rotationLeftAsked = false;
  91822. controller._rotationRightAsked = false;
  91823. controller._teleportationBackRequestInitiated = false;
  91824. }
  91825. });
  91826. }
  91827. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  91828. if (_this.teleportationEnabled) {
  91829. _this._checkTeleportBackwards(stateObject, controller);
  91830. _this._checkTeleportWithRay(stateObject, controller);
  91831. }
  91832. _this._checkRotate(stateObject, controller);
  91833. });
  91834. }
  91835. };
  91836. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  91837. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  91838. this._teleportationTarget.isPickable = false;
  91839. var length = 512;
  91840. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  91841. dynamicTexture.hasAlpha = true;
  91842. var context = dynamicTexture.getContext();
  91843. var centerX = length / 2;
  91844. var centerY = length / 2;
  91845. var radius = 200;
  91846. context.beginPath();
  91847. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  91848. context.fillStyle = this._teleportationFillColor;
  91849. context.fill();
  91850. context.lineWidth = 10;
  91851. context.strokeStyle = this._teleportationBorderColor;
  91852. context.stroke();
  91853. context.closePath();
  91854. dynamicTexture.update();
  91855. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  91856. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  91857. this._teleportationTarget.material = teleportationCircleMaterial;
  91858. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  91859. torus.isPickable = false;
  91860. torus.parent = this._teleportationTarget;
  91861. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  91862. var keys = [];
  91863. keys.push({
  91864. frame: 0,
  91865. value: 0
  91866. });
  91867. keys.push({
  91868. frame: 30,
  91869. value: 0.4
  91870. });
  91871. keys.push({
  91872. frame: 60,
  91873. value: 0
  91874. });
  91875. animationInnerCircle.setKeys(keys);
  91876. var easingFunction = new BABYLON.SineEase();
  91877. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  91878. animationInnerCircle.setEasingFunction(easingFunction);
  91879. torus.animations = [];
  91880. torus.animations.push(animationInnerCircle);
  91881. this._scene.beginAnimation(torus, 0, 60, true);
  91882. this._hideTeleportationTarget();
  91883. };
  91884. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  91885. this._teleportActive = true;
  91886. if (this._teleportationInitialized) {
  91887. this._teleportationTarget.isVisible = true;
  91888. if (this._isDefaultTeleportationTarget) {
  91889. this._teleportationTarget.getChildren()[0].isVisible = true;
  91890. }
  91891. }
  91892. };
  91893. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  91894. this._teleportActive = false;
  91895. if (this._teleportationInitialized) {
  91896. this._teleportationTarget.isVisible = false;
  91897. if (this._isDefaultTeleportationTarget) {
  91898. this._teleportationTarget.getChildren()[0].isVisible = false;
  91899. }
  91900. }
  91901. };
  91902. VRExperienceHelper.prototype._rotateCamera = function (right) {
  91903. var _this = this;
  91904. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  91905. return;
  91906. }
  91907. if (right) {
  91908. this._rotationAngle++;
  91909. }
  91910. else {
  91911. this._rotationAngle--;
  91912. }
  91913. this.currentVRCamera.animations = [];
  91914. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  91915. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91916. var animationRotationKeys = [];
  91917. animationRotationKeys.push({
  91918. frame: 0,
  91919. value: this.currentVRCamera.rotationQuaternion
  91920. });
  91921. animationRotationKeys.push({
  91922. frame: 6,
  91923. value: target
  91924. });
  91925. animationRotation.setKeys(animationRotationKeys);
  91926. animationRotation.setEasingFunction(this._circleEase);
  91927. this.currentVRCamera.animations.push(animationRotation);
  91928. this._postProcessMove.animations = [];
  91929. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91930. var vignetteWeightKeys = [];
  91931. vignetteWeightKeys.push({
  91932. frame: 0,
  91933. value: 0
  91934. });
  91935. vignetteWeightKeys.push({
  91936. frame: 3,
  91937. value: 4
  91938. });
  91939. vignetteWeightKeys.push({
  91940. frame: 6,
  91941. value: 0
  91942. });
  91943. animationPP.setKeys(vignetteWeightKeys);
  91944. animationPP.setEasingFunction(this._circleEase);
  91945. this._postProcessMove.animations.push(animationPP);
  91946. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91947. var vignetteStretchKeys = [];
  91948. vignetteStretchKeys.push({
  91949. frame: 0,
  91950. value: 0
  91951. });
  91952. vignetteStretchKeys.push({
  91953. frame: 3,
  91954. value: 10
  91955. });
  91956. vignetteStretchKeys.push({
  91957. frame: 6,
  91958. value: 0
  91959. });
  91960. animationPP2.setKeys(vignetteStretchKeys);
  91961. animationPP2.setEasingFunction(this._circleEase);
  91962. this._postProcessMove.animations.push(animationPP2);
  91963. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  91964. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  91965. this._postProcessMove.samples = 4;
  91966. this._webVRCamera.attachPostProcess(this._postProcessMove);
  91967. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  91968. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  91969. });
  91970. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  91971. };
  91972. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  91973. if (hit.pickedPoint) {
  91974. if (gazer._teleportationRequestInitiated) {
  91975. this._displayTeleportationTarget();
  91976. this._haloCenter.copyFrom(hit.pickedPoint);
  91977. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  91978. }
  91979. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  91980. if (pickNormal) {
  91981. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  91982. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  91983. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  91984. }
  91985. this._teleportationTarget.position.y += 0.1;
  91986. }
  91987. };
  91988. VRExperienceHelper.prototype._teleportCamera = function (location) {
  91989. var _this = this;
  91990. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  91991. return;
  91992. }
  91993. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  91994. // offset of the headset from the anchor.
  91995. if (this.webVRCamera.leftCamera) {
  91996. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  91997. this._workingVector.subtractInPlace(this.webVRCamera.position);
  91998. location.subtractToRef(this._workingVector, this._workingVector);
  91999. }
  92000. else {
  92001. this._workingVector.copyFrom(location);
  92002. }
  92003. // Add height to account for user's height offset
  92004. if (this.isInVRMode) {
  92005. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  92006. }
  92007. else {
  92008. this._workingVector.y += this._defaultHeight;
  92009. }
  92010. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  92011. // Create animation from the camera's position to the new location
  92012. this.currentVRCamera.animations = [];
  92013. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92014. var animationCameraTeleportationKeys = [{
  92015. frame: 0,
  92016. value: this.currentVRCamera.position
  92017. },
  92018. {
  92019. frame: 11,
  92020. value: this._workingVector
  92021. }
  92022. ];
  92023. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  92024. animationCameraTeleportation.setEasingFunction(this._circleEase);
  92025. this.currentVRCamera.animations.push(animationCameraTeleportation);
  92026. this._postProcessMove.animations = [];
  92027. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92028. var vignetteWeightKeys = [];
  92029. vignetteWeightKeys.push({
  92030. frame: 0,
  92031. value: 0
  92032. });
  92033. vignetteWeightKeys.push({
  92034. frame: 5,
  92035. value: 8
  92036. });
  92037. vignetteWeightKeys.push({
  92038. frame: 11,
  92039. value: 0
  92040. });
  92041. animationPP.setKeys(vignetteWeightKeys);
  92042. this._postProcessMove.animations.push(animationPP);
  92043. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92044. var vignetteStretchKeys = [];
  92045. vignetteStretchKeys.push({
  92046. frame: 0,
  92047. value: 0
  92048. });
  92049. vignetteStretchKeys.push({
  92050. frame: 5,
  92051. value: 10
  92052. });
  92053. vignetteStretchKeys.push({
  92054. frame: 11,
  92055. value: 0
  92056. });
  92057. animationPP2.setKeys(vignetteStretchKeys);
  92058. this._postProcessMove.animations.push(animationPP2);
  92059. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  92060. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  92061. this._webVRCamera.attachPostProcess(this._postProcessMove);
  92062. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  92063. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  92064. });
  92065. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  92066. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  92067. });
  92068. this._hideTeleportationTarget();
  92069. };
  92070. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  92071. if (normal) {
  92072. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  92073. if (angle < Math.PI / 2) {
  92074. normal.scaleInPlace(-1);
  92075. }
  92076. }
  92077. return normal;
  92078. };
  92079. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  92080. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  92081. return;
  92082. }
  92083. var ray = gazer._getForwardRay(this._rayLength);
  92084. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  92085. if (hit) {
  92086. // Populate the contrllers mesh that can be used for drag/drop
  92087. if (gazer._laserPointer) {
  92088. hit.originMesh = gazer._laserPointer.parent;
  92089. }
  92090. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  92091. }
  92092. gazer._currentHit = hit;
  92093. // Moving the gazeTracker on the mesh face targetted
  92094. if (hit && hit.pickedPoint) {
  92095. if (this._displayGaze) {
  92096. var multiplier = 1;
  92097. gazer._gazeTracker.isVisible = true;
  92098. if (gazer._isActionableMesh) {
  92099. multiplier = 3;
  92100. }
  92101. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  92102. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  92103. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  92104. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  92105. // To avoid z-fighting
  92106. var deltaFighting = 0.002;
  92107. if (pickNormal) {
  92108. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  92109. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  92110. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  92111. }
  92112. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  92113. if (gazer._gazeTracker.position.x < 0) {
  92114. gazer._gazeTracker.position.x += deltaFighting;
  92115. }
  92116. else {
  92117. gazer._gazeTracker.position.x -= deltaFighting;
  92118. }
  92119. if (gazer._gazeTracker.position.y < 0) {
  92120. gazer._gazeTracker.position.y += deltaFighting;
  92121. }
  92122. else {
  92123. gazer._gazeTracker.position.y -= deltaFighting;
  92124. }
  92125. if (gazer._gazeTracker.position.z < 0) {
  92126. gazer._gazeTracker.position.z += deltaFighting;
  92127. }
  92128. else {
  92129. gazer._gazeTracker.position.z -= deltaFighting;
  92130. }
  92131. }
  92132. // Changing the size of the laser pointer based on the distance from the targetted point
  92133. gazer._updatePointerDistance(hit.distance);
  92134. }
  92135. else {
  92136. gazer._updatePointerDistance();
  92137. gazer._gazeTracker.isVisible = false;
  92138. }
  92139. if (hit && hit.pickedMesh) {
  92140. // The object selected is the floor, we're in a teleportation scenario
  92141. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  92142. // Moving the teleportation area to this targetted point
  92143. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  92144. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  92145. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  92146. }
  92147. gazer._currentMeshSelected = null;
  92148. if (gazer._teleportationRequestInitiated) {
  92149. this._moveTeleportationSelectorTo(hit, gazer, ray);
  92150. }
  92151. return;
  92152. }
  92153. // If not, we're in a selection scenario
  92154. //this._teleportationAllowed = false;
  92155. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  92156. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  92157. this.onNewMeshPicked.notifyObservers(hit);
  92158. gazer._currentMeshSelected = hit.pickedMesh;
  92159. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  92160. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  92161. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  92162. gazer._isActionableMesh = true;
  92163. }
  92164. else {
  92165. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92166. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92167. gazer._isActionableMesh = false;
  92168. }
  92169. try {
  92170. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  92171. }
  92172. catch (err) {
  92173. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  92174. }
  92175. }
  92176. else {
  92177. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  92178. gazer._currentMeshSelected = null;
  92179. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92180. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92181. }
  92182. }
  92183. }
  92184. else {
  92185. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  92186. gazer._currentMeshSelected = null;
  92187. //this._teleportationAllowed = false;
  92188. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92189. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92190. }
  92191. };
  92192. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  92193. if (mesh) {
  92194. this.onSelectedMeshUnselected.notifyObservers(mesh);
  92195. }
  92196. };
  92197. /**
  92198. * Sets the color of the laser ray from the vr controllers.
  92199. * @param color new color for the ray.
  92200. */
  92201. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  92202. if (this.leftController) {
  92203. this.leftController._setLaserPointerColor(color);
  92204. }
  92205. if (this.rightController) {
  92206. this.rightController._setLaserPointerColor(color);
  92207. }
  92208. };
  92209. /**
  92210. * Sets the color of the ray from the vr headsets gaze.
  92211. * @param color new color for the ray.
  92212. */
  92213. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  92214. if (!this._cameraGazer._gazeTracker.material) {
  92215. return;
  92216. }
  92217. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  92218. if (this.leftController) {
  92219. this.leftController._gazeTracker.material.emissiveColor = color;
  92220. }
  92221. if (this.rightController) {
  92222. this.rightController._gazeTracker.material.emissiveColor = color;
  92223. }
  92224. };
  92225. /**
  92226. * Exits VR and disposes of the vr experience helper
  92227. */
  92228. VRExperienceHelper.prototype.dispose = function () {
  92229. if (this.isInVRMode) {
  92230. this.exitVR();
  92231. }
  92232. if (this._postProcessMove) {
  92233. this._postProcessMove.dispose();
  92234. }
  92235. if (this._webVRCamera) {
  92236. this._webVRCamera.dispose();
  92237. }
  92238. if (this._vrDeviceOrientationCamera) {
  92239. this._vrDeviceOrientationCamera.dispose();
  92240. }
  92241. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  92242. document.body.removeChild(this._btnVR);
  92243. }
  92244. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  92245. this._deviceOrientationCamera.dispose();
  92246. }
  92247. if (this._cameraGazer) {
  92248. this._cameraGazer.dispose();
  92249. }
  92250. if (this.leftController) {
  92251. this.leftController.dispose();
  92252. }
  92253. if (this.rightController) {
  92254. this.rightController.dispose();
  92255. }
  92256. if (this._teleportationTarget) {
  92257. this._teleportationTarget.dispose();
  92258. }
  92259. this._floorMeshesCollection = [];
  92260. document.removeEventListener("keydown", this._onKeyDown);
  92261. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  92262. window.removeEventListener("resize", this._onResize);
  92263. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  92264. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  92265. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  92266. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  92267. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  92268. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  92269. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  92270. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  92271. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  92272. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  92273. this._scene.unregisterBeforeRender(this.beforeRender);
  92274. };
  92275. /**
  92276. * Gets the name of the VRExperienceHelper class
  92277. * @returns "VRExperienceHelper"
  92278. */
  92279. VRExperienceHelper.prototype.getClassName = function () {
  92280. return "VRExperienceHelper";
  92281. };
  92282. return VRExperienceHelper;
  92283. }());
  92284. BABYLON.VRExperienceHelper = VRExperienceHelper;
  92285. })(BABYLON || (BABYLON = {}));
  92286. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  92287. // Mainly based on these 2 articles :
  92288. // 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
  92289. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  92290. var BABYLON;
  92291. (function (BABYLON) {
  92292. /**
  92293. * Defines the potential axis of a Joystick
  92294. */
  92295. var JoystickAxis;
  92296. (function (JoystickAxis) {
  92297. /** X axis */
  92298. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  92299. /** Y axis */
  92300. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  92301. /** Z axis */
  92302. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  92303. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  92304. /**
  92305. * Class used to define virtual joystick (used in touch mode)
  92306. */
  92307. var VirtualJoystick = /** @class */ (function () {
  92308. /**
  92309. * Creates a new virtual joystick
  92310. * @param leftJoystick defines that the joystick is for left hand (false by default)
  92311. */
  92312. function VirtualJoystick(leftJoystick) {
  92313. var _this = this;
  92314. if (leftJoystick) {
  92315. this._leftJoystick = true;
  92316. }
  92317. else {
  92318. this._leftJoystick = false;
  92319. }
  92320. VirtualJoystick._globalJoystickIndex++;
  92321. // By default left & right arrow keys are moving the X
  92322. // and up & down keys are moving the Y
  92323. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  92324. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  92325. this.reverseLeftRight = false;
  92326. this.reverseUpDown = false;
  92327. // collections of pointers
  92328. this._touches = new BABYLON.StringDictionary();
  92329. this.deltaPosition = BABYLON.Vector3.Zero();
  92330. this._joystickSensibility = 25;
  92331. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  92332. this._onResize = function (evt) {
  92333. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  92334. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  92335. if (VirtualJoystick.vjCanvas) {
  92336. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  92337. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  92338. }
  92339. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  92340. };
  92341. // injecting a canvas element on top of the canvas 3D game
  92342. if (!VirtualJoystick.vjCanvas) {
  92343. window.addEventListener("resize", this._onResize, false);
  92344. VirtualJoystick.vjCanvas = document.createElement("canvas");
  92345. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  92346. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  92347. VirtualJoystick.vjCanvas.width = window.innerWidth;
  92348. VirtualJoystick.vjCanvas.height = window.innerHeight;
  92349. VirtualJoystick.vjCanvas.style.width = "100%";
  92350. VirtualJoystick.vjCanvas.style.height = "100%";
  92351. VirtualJoystick.vjCanvas.style.position = "absolute";
  92352. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  92353. VirtualJoystick.vjCanvas.style.top = "0px";
  92354. VirtualJoystick.vjCanvas.style.left = "0px";
  92355. VirtualJoystick.vjCanvas.style.zIndex = "5";
  92356. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  92357. // Support for jQuery PEP polyfill
  92358. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  92359. var context = VirtualJoystick.vjCanvas.getContext('2d');
  92360. if (!context) {
  92361. throw new Error("Unable to create canvas for virtual joystick");
  92362. }
  92363. VirtualJoystick.vjCanvasContext = context;
  92364. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  92365. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  92366. document.body.appendChild(VirtualJoystick.vjCanvas);
  92367. }
  92368. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  92369. this.pressed = false;
  92370. // default joystick color
  92371. this._joystickColor = "cyan";
  92372. this._joystickPointerID = -1;
  92373. // current joystick position
  92374. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  92375. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  92376. // origin joystick position
  92377. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  92378. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  92379. this._onPointerDownHandlerRef = function (evt) {
  92380. _this._onPointerDown(evt);
  92381. };
  92382. this._onPointerMoveHandlerRef = function (evt) {
  92383. _this._onPointerMove(evt);
  92384. };
  92385. this._onPointerUpHandlerRef = function (evt) {
  92386. _this._onPointerUp(evt);
  92387. };
  92388. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  92389. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  92390. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  92391. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  92392. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  92393. evt.preventDefault(); // Disables system menu
  92394. }, false);
  92395. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  92396. }
  92397. /**
  92398. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  92399. * @param newJoystickSensibility defines the new sensibility
  92400. */
  92401. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  92402. this._joystickSensibility = newJoystickSensibility;
  92403. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  92404. };
  92405. VirtualJoystick.prototype._onPointerDown = function (e) {
  92406. var positionOnScreenCondition;
  92407. e.preventDefault();
  92408. if (this._leftJoystick === true) {
  92409. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  92410. }
  92411. else {
  92412. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  92413. }
  92414. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  92415. // First contact will be dedicated to the virtual joystick
  92416. this._joystickPointerID = e.pointerId;
  92417. this._joystickPointerStartPos.x = e.clientX;
  92418. this._joystickPointerStartPos.y = e.clientY;
  92419. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  92420. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  92421. this._deltaJoystickVector.x = 0;
  92422. this._deltaJoystickVector.y = 0;
  92423. this.pressed = true;
  92424. this._touches.add(e.pointerId.toString(), e);
  92425. }
  92426. else {
  92427. // You can only trigger the action buttons with a joystick declared
  92428. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  92429. this._action();
  92430. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  92431. }
  92432. }
  92433. };
  92434. VirtualJoystick.prototype._onPointerMove = function (e) {
  92435. // If the current pointer is the one associated to the joystick (first touch contact)
  92436. if (this._joystickPointerID == e.pointerId) {
  92437. this._joystickPointerPos.x = e.clientX;
  92438. this._joystickPointerPos.y = e.clientY;
  92439. this._deltaJoystickVector = this._joystickPointerPos.clone();
  92440. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  92441. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  92442. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  92443. switch (this._axisTargetedByLeftAndRight) {
  92444. case JoystickAxis.X:
  92445. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  92446. break;
  92447. case JoystickAxis.Y:
  92448. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  92449. break;
  92450. case JoystickAxis.Z:
  92451. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  92452. break;
  92453. }
  92454. var directionUpDown = this.reverseUpDown ? 1 : -1;
  92455. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  92456. switch (this._axisTargetedByUpAndDown) {
  92457. case JoystickAxis.X:
  92458. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  92459. break;
  92460. case JoystickAxis.Y:
  92461. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  92462. break;
  92463. case JoystickAxis.Z:
  92464. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  92465. break;
  92466. }
  92467. }
  92468. else {
  92469. var data = this._touches.get(e.pointerId.toString());
  92470. if (data) {
  92471. data.x = e.clientX;
  92472. data.y = e.clientY;
  92473. }
  92474. }
  92475. };
  92476. VirtualJoystick.prototype._onPointerUp = function (e) {
  92477. if (this._joystickPointerID == e.pointerId) {
  92478. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  92479. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  92480. this._joystickPointerID = -1;
  92481. this.pressed = false;
  92482. }
  92483. else {
  92484. var touch = this._touches.get(e.pointerId.toString());
  92485. if (touch) {
  92486. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  92487. }
  92488. }
  92489. this._deltaJoystickVector.x = 0;
  92490. this._deltaJoystickVector.y = 0;
  92491. this._touches.remove(e.pointerId.toString());
  92492. };
  92493. /**
  92494. * Change the color of the virtual joystick
  92495. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  92496. */
  92497. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  92498. this._joystickColor = newColor;
  92499. };
  92500. /**
  92501. * Defines a callback to call when the joystick is touched
  92502. * @param action defines the callback
  92503. */
  92504. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  92505. this._action = action;
  92506. };
  92507. /**
  92508. * Defines which axis you'd like to control for left & right
  92509. * @param axis defines the axis to use
  92510. */
  92511. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  92512. switch (axis) {
  92513. case JoystickAxis.X:
  92514. case JoystickAxis.Y:
  92515. case JoystickAxis.Z:
  92516. this._axisTargetedByLeftAndRight = axis;
  92517. break;
  92518. default:
  92519. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  92520. break;
  92521. }
  92522. };
  92523. /**
  92524. * Defines which axis you'd like to control for up & down
  92525. * @param axis defines the axis to use
  92526. */
  92527. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  92528. switch (axis) {
  92529. case JoystickAxis.X:
  92530. case JoystickAxis.Y:
  92531. case JoystickAxis.Z:
  92532. this._axisTargetedByUpAndDown = axis;
  92533. break;
  92534. default:
  92535. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  92536. break;
  92537. }
  92538. };
  92539. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  92540. var _this = this;
  92541. if (this.pressed) {
  92542. this._touches.forEach(function (key, touch) {
  92543. if (touch.pointerId === _this._joystickPointerID) {
  92544. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  92545. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  92546. VirtualJoystick.vjCanvasContext.beginPath();
  92547. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  92548. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  92549. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  92550. VirtualJoystick.vjCanvasContext.stroke();
  92551. VirtualJoystick.vjCanvasContext.closePath();
  92552. VirtualJoystick.vjCanvasContext.beginPath();
  92553. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  92554. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  92555. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  92556. VirtualJoystick.vjCanvasContext.stroke();
  92557. VirtualJoystick.vjCanvasContext.closePath();
  92558. VirtualJoystick.vjCanvasContext.beginPath();
  92559. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  92560. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  92561. VirtualJoystick.vjCanvasContext.stroke();
  92562. VirtualJoystick.vjCanvasContext.closePath();
  92563. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  92564. }
  92565. else {
  92566. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  92567. VirtualJoystick.vjCanvasContext.beginPath();
  92568. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  92569. VirtualJoystick.vjCanvasContext.beginPath();
  92570. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  92571. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  92572. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  92573. VirtualJoystick.vjCanvasContext.stroke();
  92574. VirtualJoystick.vjCanvasContext.closePath();
  92575. touch.prevX = touch.x;
  92576. touch.prevY = touch.y;
  92577. }
  92578. ;
  92579. });
  92580. }
  92581. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  92582. };
  92583. /**
  92584. * Release internal HTML canvas
  92585. */
  92586. VirtualJoystick.prototype.releaseCanvas = function () {
  92587. if (VirtualJoystick.vjCanvas) {
  92588. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  92589. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  92590. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  92591. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  92592. window.removeEventListener("resize", this._onResize);
  92593. document.body.removeChild(VirtualJoystick.vjCanvas);
  92594. VirtualJoystick.vjCanvas = null;
  92595. }
  92596. };
  92597. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  92598. VirtualJoystick._globalJoystickIndex = 0;
  92599. return VirtualJoystick;
  92600. }());
  92601. BABYLON.VirtualJoystick = VirtualJoystick;
  92602. })(BABYLON || (BABYLON = {}));
  92603. //# sourceMappingURL=babylon.virtualJoystick.js.map
  92604. var BABYLON;
  92605. (function (BABYLON) {
  92606. // We're mainly based on the logic defined into the FreeCamera code
  92607. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  92608. __extends(VirtualJoysticksCamera, _super);
  92609. function VirtualJoysticksCamera(name, position, scene) {
  92610. var _this = _super.call(this, name, position, scene) || this;
  92611. _this.inputs.addVirtualJoystick();
  92612. return _this;
  92613. }
  92614. VirtualJoysticksCamera.prototype.getClassName = function () {
  92615. return "VirtualJoysticksCamera";
  92616. };
  92617. return VirtualJoysticksCamera;
  92618. }(BABYLON.FreeCamera));
  92619. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  92620. })(BABYLON || (BABYLON = {}));
  92621. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  92622. var BABYLON;
  92623. (function (BABYLON) {
  92624. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  92625. function FreeCameraVirtualJoystickInput() {
  92626. }
  92627. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  92628. return this._leftjoystick;
  92629. };
  92630. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  92631. return this._rightjoystick;
  92632. };
  92633. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  92634. if (this._leftjoystick) {
  92635. var camera = this.camera;
  92636. var speed = camera._computeLocalCameraSpeed() * 50;
  92637. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  92638. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  92639. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  92640. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  92641. if (!this._leftjoystick.pressed) {
  92642. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  92643. }
  92644. if (!this._rightjoystick.pressed) {
  92645. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  92646. }
  92647. }
  92648. };
  92649. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  92650. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  92651. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  92652. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  92653. this._leftjoystick.setJoystickSensibility(0.15);
  92654. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  92655. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  92656. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  92657. this._rightjoystick.reverseUpDown = true;
  92658. this._rightjoystick.setJoystickSensibility(0.05);
  92659. this._rightjoystick.setJoystickColor("yellow");
  92660. };
  92661. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  92662. this._leftjoystick.releaseCanvas();
  92663. this._rightjoystick.releaseCanvas();
  92664. };
  92665. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  92666. return "FreeCameraVirtualJoystickInput";
  92667. };
  92668. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  92669. return "virtualJoystick";
  92670. };
  92671. return FreeCameraVirtualJoystickInput;
  92672. }());
  92673. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  92674. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  92675. })(BABYLON || (BABYLON = {}));
  92676. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  92677. var BABYLON;
  92678. (function (BABYLON) {
  92679. var SimplificationSettings = /** @class */ (function () {
  92680. function SimplificationSettings(quality, distance, optimizeMesh) {
  92681. this.quality = quality;
  92682. this.distance = distance;
  92683. this.optimizeMesh = optimizeMesh;
  92684. }
  92685. return SimplificationSettings;
  92686. }());
  92687. BABYLON.SimplificationSettings = SimplificationSettings;
  92688. var SimplificationQueue = /** @class */ (function () {
  92689. function SimplificationQueue() {
  92690. this.running = false;
  92691. this._simplificationArray = [];
  92692. }
  92693. SimplificationQueue.prototype.addTask = function (task) {
  92694. this._simplificationArray.push(task);
  92695. };
  92696. SimplificationQueue.prototype.executeNext = function () {
  92697. var task = this._simplificationArray.pop();
  92698. if (task) {
  92699. this.running = true;
  92700. this.runSimplification(task);
  92701. }
  92702. else {
  92703. this.running = false;
  92704. }
  92705. };
  92706. SimplificationQueue.prototype.runSimplification = function (task) {
  92707. var _this = this;
  92708. if (task.parallelProcessing) {
  92709. //parallel simplifier
  92710. task.settings.forEach(function (setting) {
  92711. var simplifier = _this.getSimplifier(task);
  92712. simplifier.simplify(setting, function (newMesh) {
  92713. task.mesh.addLODLevel(setting.distance, newMesh);
  92714. newMesh.isVisible = true;
  92715. //check if it is the last
  92716. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  92717. //all done, run the success callback.
  92718. task.successCallback();
  92719. }
  92720. _this.executeNext();
  92721. });
  92722. });
  92723. }
  92724. else {
  92725. //single simplifier.
  92726. var simplifier = this.getSimplifier(task);
  92727. var runDecimation = function (setting, callback) {
  92728. simplifier.simplify(setting, function (newMesh) {
  92729. task.mesh.addLODLevel(setting.distance, newMesh);
  92730. newMesh.isVisible = true;
  92731. //run the next quality level
  92732. callback();
  92733. });
  92734. };
  92735. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  92736. runDecimation(task.settings[loop.index], function () {
  92737. loop.executeNext();
  92738. });
  92739. }, function () {
  92740. //execution ended, run the success callback.
  92741. if (task.successCallback) {
  92742. task.successCallback();
  92743. }
  92744. _this.executeNext();
  92745. });
  92746. }
  92747. };
  92748. SimplificationQueue.prototype.getSimplifier = function (task) {
  92749. switch (task.simplificationType) {
  92750. case SimplificationType.QUADRATIC:
  92751. default:
  92752. return new QuadraticErrorSimplification(task.mesh);
  92753. }
  92754. };
  92755. return SimplificationQueue;
  92756. }());
  92757. BABYLON.SimplificationQueue = SimplificationQueue;
  92758. /**
  92759. * The implemented types of simplification
  92760. * At the moment only Quadratic Error Decimation is implemented
  92761. */
  92762. var SimplificationType;
  92763. (function (SimplificationType) {
  92764. /** Quadratic error decimation */
  92765. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  92766. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  92767. var DecimationTriangle = /** @class */ (function () {
  92768. function DecimationTriangle(vertices) {
  92769. this.vertices = vertices;
  92770. this.error = new Array(4);
  92771. this.deleted = false;
  92772. this.isDirty = false;
  92773. this.deletePending = false;
  92774. this.borderFactor = 0;
  92775. }
  92776. return DecimationTriangle;
  92777. }());
  92778. BABYLON.DecimationTriangle = DecimationTriangle;
  92779. var DecimationVertex = /** @class */ (function () {
  92780. function DecimationVertex(position, id) {
  92781. this.position = position;
  92782. this.id = id;
  92783. this.isBorder = true;
  92784. this.q = new QuadraticMatrix();
  92785. this.triangleCount = 0;
  92786. this.triangleStart = 0;
  92787. this.originalOffsets = [];
  92788. }
  92789. DecimationVertex.prototype.updatePosition = function (newPosition) {
  92790. this.position.copyFrom(newPosition);
  92791. };
  92792. return DecimationVertex;
  92793. }());
  92794. BABYLON.DecimationVertex = DecimationVertex;
  92795. var QuadraticMatrix = /** @class */ (function () {
  92796. function QuadraticMatrix(data) {
  92797. this.data = new Array(10);
  92798. for (var i = 0; i < 10; ++i) {
  92799. if (data && data[i]) {
  92800. this.data[i] = data[i];
  92801. }
  92802. else {
  92803. this.data[i] = 0;
  92804. }
  92805. }
  92806. }
  92807. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  92808. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  92809. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  92810. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  92811. return det;
  92812. };
  92813. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  92814. for (var i = 0; i < 10; ++i) {
  92815. this.data[i] += matrix.data[i];
  92816. }
  92817. };
  92818. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  92819. for (var i = 0; i < 10; ++i) {
  92820. this.data[i] += data[i];
  92821. }
  92822. };
  92823. QuadraticMatrix.prototype.add = function (matrix) {
  92824. var m = new QuadraticMatrix();
  92825. for (var i = 0; i < 10; ++i) {
  92826. m.data[i] = this.data[i] + matrix.data[i];
  92827. }
  92828. return m;
  92829. };
  92830. QuadraticMatrix.FromData = function (a, b, c, d) {
  92831. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  92832. };
  92833. //returning an array to avoid garbage collection
  92834. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  92835. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  92836. };
  92837. return QuadraticMatrix;
  92838. }());
  92839. BABYLON.QuadraticMatrix = QuadraticMatrix;
  92840. var Reference = /** @class */ (function () {
  92841. function Reference(vertexId, triangleId) {
  92842. this.vertexId = vertexId;
  92843. this.triangleId = triangleId;
  92844. }
  92845. return Reference;
  92846. }());
  92847. BABYLON.Reference = Reference;
  92848. /**
  92849. * An implementation of the Quadratic Error simplification algorithm.
  92850. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  92851. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  92852. * @author RaananW
  92853. */
  92854. var QuadraticErrorSimplification = /** @class */ (function () {
  92855. function QuadraticErrorSimplification(_mesh) {
  92856. this._mesh = _mesh;
  92857. this.syncIterations = 5000;
  92858. this.aggressiveness = 7;
  92859. this.decimationIterations = 100;
  92860. this.boundingBoxEpsilon = BABYLON.Epsilon;
  92861. }
  92862. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  92863. var _this = this;
  92864. this.initDecimatedMesh();
  92865. //iterating through the submeshes array, one after the other.
  92866. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  92867. _this.initWithMesh(loop.index, function () {
  92868. _this.runDecimation(settings, loop.index, function () {
  92869. loop.executeNext();
  92870. });
  92871. }, settings.optimizeMesh);
  92872. }, function () {
  92873. setTimeout(function () {
  92874. successCallback(_this._reconstructedMesh);
  92875. }, 0);
  92876. });
  92877. };
  92878. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  92879. var _this = this;
  92880. var targetCount = ~~(this.triangles.length * settings.quality);
  92881. var deletedTriangles = 0;
  92882. var triangleCount = this.triangles.length;
  92883. var iterationFunction = function (iteration, callback) {
  92884. setTimeout(function () {
  92885. if (iteration % 5 === 0) {
  92886. _this.updateMesh(iteration === 0);
  92887. }
  92888. for (var i = 0; i < _this.triangles.length; ++i) {
  92889. _this.triangles[i].isDirty = false;
  92890. }
  92891. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  92892. var trianglesIterator = function (i) {
  92893. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  92894. var t = _this.triangles[tIdx];
  92895. if (!t)
  92896. return;
  92897. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  92898. return;
  92899. }
  92900. for (var j = 0; j < 3; ++j) {
  92901. if (t.error[j] < threshold) {
  92902. var deleted0 = [];
  92903. var deleted1 = [];
  92904. var v0 = t.vertices[j];
  92905. var v1 = t.vertices[(j + 1) % 3];
  92906. if (v0.isBorder || v1.isBorder)
  92907. continue;
  92908. var p = BABYLON.Vector3.Zero();
  92909. var n = BABYLON.Vector3.Zero();
  92910. var uv = BABYLON.Vector2.Zero();
  92911. var color = new BABYLON.Color4(0, 0, 0, 1);
  92912. _this.calculateError(v0, v1, p, n, uv, color);
  92913. var delTr = new Array();
  92914. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  92915. continue;
  92916. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  92917. continue;
  92918. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  92919. continue;
  92920. var uniqueArray = new Array();
  92921. delTr.forEach(function (deletedT) {
  92922. if (uniqueArray.indexOf(deletedT) === -1) {
  92923. deletedT.deletePending = true;
  92924. uniqueArray.push(deletedT);
  92925. }
  92926. });
  92927. if (uniqueArray.length % 2 !== 0) {
  92928. continue;
  92929. }
  92930. v0.q = v1.q.add(v0.q);
  92931. v0.updatePosition(p);
  92932. var tStart = _this.references.length;
  92933. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  92934. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  92935. var tCount = _this.references.length - tStart;
  92936. if (tCount <= v0.triangleCount) {
  92937. if (tCount) {
  92938. for (var c = 0; c < tCount; c++) {
  92939. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  92940. }
  92941. }
  92942. }
  92943. else {
  92944. v0.triangleStart = tStart;
  92945. }
  92946. v0.triangleCount = tCount;
  92947. break;
  92948. }
  92949. }
  92950. };
  92951. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  92952. }, 0);
  92953. };
  92954. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  92955. if (triangleCount - deletedTriangles <= targetCount)
  92956. loop.breakLoop();
  92957. else {
  92958. iterationFunction(loop.index, function () {
  92959. loop.executeNext();
  92960. });
  92961. }
  92962. }, function () {
  92963. setTimeout(function () {
  92964. //reconstruct this part of the mesh
  92965. _this.reconstructMesh(submeshIndex);
  92966. successCallback();
  92967. }, 0);
  92968. });
  92969. };
  92970. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  92971. var _this = this;
  92972. this.vertices = [];
  92973. this.triangles = [];
  92974. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  92975. var indices = this._mesh.getIndices();
  92976. var submesh = this._mesh.subMeshes[submeshIndex];
  92977. var findInVertices = function (positionToSearch) {
  92978. if (optimizeMesh) {
  92979. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  92980. if (_this.vertices[ii].position.equals(positionToSearch)) {
  92981. return _this.vertices[ii];
  92982. }
  92983. }
  92984. }
  92985. return null;
  92986. };
  92987. var vertexReferences = [];
  92988. var vertexInit = function (i) {
  92989. if (!positionData) {
  92990. return;
  92991. }
  92992. var offset = i + submesh.verticesStart;
  92993. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  92994. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  92995. vertex.originalOffsets.push(offset);
  92996. if (vertex.id === _this.vertices.length) {
  92997. _this.vertices.push(vertex);
  92998. }
  92999. vertexReferences.push(vertex.id);
  93000. };
  93001. //var totalVertices = mesh.getTotalVertices();
  93002. var totalVertices = submesh.verticesCount;
  93003. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  93004. var indicesInit = function (i) {
  93005. if (!indices) {
  93006. return;
  93007. }
  93008. var offset = (submesh.indexStart / 3) + i;
  93009. var pos = (offset * 3);
  93010. var i0 = indices[pos + 0];
  93011. var i1 = indices[pos + 1];
  93012. var i2 = indices[pos + 2];
  93013. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  93014. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  93015. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  93016. var triangle = new DecimationTriangle([v0, v1, v2]);
  93017. triangle.originalOffset = pos;
  93018. _this.triangles.push(triangle);
  93019. };
  93020. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  93021. _this.init(callback);
  93022. });
  93023. });
  93024. };
  93025. QuadraticErrorSimplification.prototype.init = function (callback) {
  93026. var _this = this;
  93027. var triangleInit1 = function (i) {
  93028. var t = _this.triangles[i];
  93029. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  93030. for (var j = 0; j < 3; j++) {
  93031. 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))));
  93032. }
  93033. };
  93034. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  93035. var triangleInit2 = function (i) {
  93036. var t = _this.triangles[i];
  93037. for (var j = 0; j < 3; ++j) {
  93038. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  93039. }
  93040. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  93041. };
  93042. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  93043. callback();
  93044. });
  93045. });
  93046. };
  93047. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  93048. var newTriangles = [];
  93049. var i;
  93050. for (i = 0; i < this.vertices.length; ++i) {
  93051. this.vertices[i].triangleCount = 0;
  93052. }
  93053. var t;
  93054. var j;
  93055. for (i = 0; i < this.triangles.length; ++i) {
  93056. if (!this.triangles[i].deleted) {
  93057. t = this.triangles[i];
  93058. for (j = 0; j < 3; ++j) {
  93059. t.vertices[j].triangleCount = 1;
  93060. }
  93061. newTriangles.push(t);
  93062. }
  93063. }
  93064. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  93065. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  93066. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  93067. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  93068. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  93069. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  93070. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  93071. var vertexCount = 0;
  93072. for (i = 0; i < this.vertices.length; ++i) {
  93073. var vertex = this.vertices[i];
  93074. vertex.id = vertexCount;
  93075. if (vertex.triangleCount) {
  93076. vertex.originalOffsets.forEach(function (originalOffset) {
  93077. if (!normalData) {
  93078. return;
  93079. }
  93080. newPositionData.push(vertex.position.x);
  93081. newPositionData.push(vertex.position.y);
  93082. newPositionData.push(vertex.position.z);
  93083. newNormalData.push(normalData[originalOffset * 3]);
  93084. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  93085. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  93086. if (uvs && uvs.length) {
  93087. newUVsData.push(uvs[(originalOffset * 2)]);
  93088. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  93089. }
  93090. else if (colorsData && colorsData.length) {
  93091. newColorsData.push(colorsData[(originalOffset * 4)]);
  93092. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  93093. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  93094. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  93095. }
  93096. ++vertexCount;
  93097. });
  93098. }
  93099. }
  93100. var startingIndex = this._reconstructedMesh.getTotalIndices();
  93101. var startingVertex = this._reconstructedMesh.getTotalVertices();
  93102. var submeshesArray = this._reconstructedMesh.subMeshes;
  93103. this._reconstructedMesh.subMeshes = [];
  93104. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  93105. var originalIndices = this._mesh.getIndices();
  93106. for (i = 0; i < newTriangles.length; ++i) {
  93107. t = newTriangles[i]; //now get the new referencing point for each vertex
  93108. [0, 1, 2].forEach(function (idx) {
  93109. var id = originalIndices[t.originalOffset + idx];
  93110. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  93111. if (offset < 0)
  93112. offset = 0;
  93113. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  93114. });
  93115. }
  93116. //overwriting the old vertex buffers and indices.
  93117. this._reconstructedMesh.setIndices(newIndicesArray);
  93118. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  93119. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  93120. if (newUVsData.length > 0)
  93121. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  93122. if (newColorsData.length > 0)
  93123. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  93124. //create submesh
  93125. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  93126. if (submeshIndex > 0) {
  93127. this._reconstructedMesh.subMeshes = [];
  93128. submeshesArray.forEach(function (submesh) {
  93129. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  93130. });
  93131. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  93132. }
  93133. };
  93134. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  93135. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  93136. this._reconstructedMesh.material = this._mesh.material;
  93137. this._reconstructedMesh.parent = this._mesh.parent;
  93138. this._reconstructedMesh.isVisible = false;
  93139. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  93140. };
  93141. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  93142. for (var i = 0; i < vertex1.triangleCount; ++i) {
  93143. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  93144. if (t.deleted)
  93145. continue;
  93146. var s = this.references[vertex1.triangleStart + i].vertexId;
  93147. var v1 = t.vertices[(s + 1) % 3];
  93148. var v2 = t.vertices[(s + 2) % 3];
  93149. if ((v1 === vertex2 || v2 === vertex2)) {
  93150. deletedArray[i] = true;
  93151. delTr.push(t);
  93152. continue;
  93153. }
  93154. var d1 = v1.position.subtract(point);
  93155. d1 = d1.normalize();
  93156. var d2 = v2.position.subtract(point);
  93157. d2 = d2.normalize();
  93158. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  93159. return true;
  93160. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  93161. deletedArray[i] = false;
  93162. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  93163. return true;
  93164. }
  93165. return false;
  93166. };
  93167. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  93168. var newDeleted = deletedTriangles;
  93169. for (var i = 0; i < vertex.triangleCount; ++i) {
  93170. var ref = this.references[vertex.triangleStart + i];
  93171. var t = this.triangles[ref.triangleId];
  93172. if (t.deleted)
  93173. continue;
  93174. if (deletedArray[i] && t.deletePending) {
  93175. t.deleted = true;
  93176. newDeleted++;
  93177. continue;
  93178. }
  93179. t.vertices[ref.vertexId] = origVertex;
  93180. t.isDirty = true;
  93181. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  93182. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  93183. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  93184. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  93185. this.references.push(ref);
  93186. }
  93187. return newDeleted;
  93188. };
  93189. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  93190. for (var i = 0; i < this.vertices.length; ++i) {
  93191. var vCount = [];
  93192. var vId = [];
  93193. var v = this.vertices[i];
  93194. var j;
  93195. for (j = 0; j < v.triangleCount; ++j) {
  93196. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  93197. for (var ii = 0; ii < 3; ii++) {
  93198. var ofs = 0;
  93199. var vv = triangle.vertices[ii];
  93200. while (ofs < vCount.length) {
  93201. if (vId[ofs] === vv.id)
  93202. break;
  93203. ++ofs;
  93204. }
  93205. if (ofs === vCount.length) {
  93206. vCount.push(1);
  93207. vId.push(vv.id);
  93208. }
  93209. else {
  93210. vCount[ofs]++;
  93211. }
  93212. }
  93213. }
  93214. for (j = 0; j < vCount.length; ++j) {
  93215. if (vCount[j] === 1) {
  93216. this.vertices[vId[j]].isBorder = true;
  93217. }
  93218. else {
  93219. this.vertices[vId[j]].isBorder = false;
  93220. }
  93221. }
  93222. }
  93223. };
  93224. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  93225. if (identifyBorders === void 0) { identifyBorders = false; }
  93226. var i;
  93227. if (!identifyBorders) {
  93228. var newTrianglesVector = [];
  93229. for (i = 0; i < this.triangles.length; ++i) {
  93230. if (!this.triangles[i].deleted) {
  93231. newTrianglesVector.push(this.triangles[i]);
  93232. }
  93233. }
  93234. this.triangles = newTrianglesVector;
  93235. }
  93236. for (i = 0; i < this.vertices.length; ++i) {
  93237. this.vertices[i].triangleCount = 0;
  93238. this.vertices[i].triangleStart = 0;
  93239. }
  93240. var t;
  93241. var j;
  93242. var v;
  93243. for (i = 0; i < this.triangles.length; ++i) {
  93244. t = this.triangles[i];
  93245. for (j = 0; j < 3; ++j) {
  93246. v = t.vertices[j];
  93247. v.triangleCount++;
  93248. }
  93249. }
  93250. var tStart = 0;
  93251. for (i = 0; i < this.vertices.length; ++i) {
  93252. this.vertices[i].triangleStart = tStart;
  93253. tStart += this.vertices[i].triangleCount;
  93254. this.vertices[i].triangleCount = 0;
  93255. }
  93256. var newReferences = new Array(this.triangles.length * 3);
  93257. for (i = 0; i < this.triangles.length; ++i) {
  93258. t = this.triangles[i];
  93259. for (j = 0; j < 3; ++j) {
  93260. v = t.vertices[j];
  93261. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  93262. v.triangleCount++;
  93263. }
  93264. }
  93265. this.references = newReferences;
  93266. if (identifyBorders) {
  93267. this.identifyBorder();
  93268. }
  93269. };
  93270. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  93271. var x = point.x;
  93272. var y = point.y;
  93273. var z = point.z;
  93274. 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
  93275. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  93276. };
  93277. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  93278. var q = vertex1.q.add(vertex2.q);
  93279. var border = vertex1.isBorder && vertex2.isBorder;
  93280. var error = 0;
  93281. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  93282. if (qDet !== 0 && !border) {
  93283. if (!pointResult) {
  93284. pointResult = BABYLON.Vector3.Zero();
  93285. }
  93286. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  93287. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  93288. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  93289. error = this.vertexError(q, pointResult);
  93290. }
  93291. else {
  93292. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  93293. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  93294. var error1 = this.vertexError(q, vertex1.position);
  93295. var error2 = this.vertexError(q, vertex2.position);
  93296. var error3 = this.vertexError(q, p3);
  93297. error = Math.min(error1, error2, error3);
  93298. if (error === error1) {
  93299. if (pointResult) {
  93300. pointResult.copyFrom(vertex1.position);
  93301. }
  93302. }
  93303. else if (error === error2) {
  93304. if (pointResult) {
  93305. pointResult.copyFrom(vertex2.position);
  93306. }
  93307. }
  93308. else {
  93309. if (pointResult) {
  93310. pointResult.copyFrom(p3);
  93311. }
  93312. }
  93313. }
  93314. return error;
  93315. };
  93316. return QuadraticErrorSimplification;
  93317. }());
  93318. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  93319. })(BABYLON || (BABYLON = {}));
  93320. //# sourceMappingURL=babylon.meshSimplification.js.map
  93321. var BABYLON;
  93322. (function (BABYLON) {
  93323. var MeshLODLevel = /** @class */ (function () {
  93324. function MeshLODLevel(distance, mesh) {
  93325. this.distance = distance;
  93326. this.mesh = mesh;
  93327. }
  93328. return MeshLODLevel;
  93329. }());
  93330. BABYLON.MeshLODLevel = MeshLODLevel;
  93331. })(BABYLON || (BABYLON = {}));
  93332. //# sourceMappingURL=babylon.meshLODLevel.js.map
  93333. var BABYLON;
  93334. (function (BABYLON) {
  93335. /**
  93336. * Defines the root class used to create scene optimization to use with SceneOptimizer
  93337. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93338. */
  93339. var SceneOptimization = /** @class */ (function () {
  93340. /**
  93341. * Creates the SceneOptimization object
  93342. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  93343. * @param desc defines the description associated with the optimization
  93344. */
  93345. function SceneOptimization(
  93346. /**
  93347. * Defines the priority of this optimization (0 by default which means first in the list)
  93348. */
  93349. priority) {
  93350. if (priority === void 0) { priority = 0; }
  93351. this.priority = priority;
  93352. }
  93353. /**
  93354. * Gets a string describing the action executed by the current optimization
  93355. * @returns description string
  93356. */
  93357. SceneOptimization.prototype.getDescription = function () {
  93358. return "";
  93359. };
  93360. /**
  93361. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93362. * @param scene defines the current scene where to apply this optimization
  93363. * @param optimizer defines the current optimizer
  93364. * @returns true if everything that can be done was applied
  93365. */
  93366. SceneOptimization.prototype.apply = function (scene, optimizer) {
  93367. return true;
  93368. };
  93369. ;
  93370. return SceneOptimization;
  93371. }());
  93372. BABYLON.SceneOptimization = SceneOptimization;
  93373. /**
  93374. * Defines an optimization used to reduce the size of render target textures
  93375. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93376. */
  93377. var TextureOptimization = /** @class */ (function (_super) {
  93378. __extends(TextureOptimization, _super);
  93379. /**
  93380. * Creates the TextureOptimization object
  93381. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  93382. * @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
  93383. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  93384. */
  93385. function TextureOptimization(
  93386. /**
  93387. * Defines the priority of this optimization (0 by default which means first in the list)
  93388. */
  93389. priority,
  93390. /**
  93391. * 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
  93392. */
  93393. maximumSize,
  93394. /**
  93395. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  93396. */
  93397. step) {
  93398. if (priority === void 0) { priority = 0; }
  93399. if (maximumSize === void 0) { maximumSize = 1024; }
  93400. if (step === void 0) { step = 0.5; }
  93401. var _this = _super.call(this, priority) || this;
  93402. _this.priority = priority;
  93403. _this.maximumSize = maximumSize;
  93404. _this.step = step;
  93405. return _this;
  93406. }
  93407. /**
  93408. * Gets a string describing the action executed by the current optimization
  93409. * @returns description string
  93410. */
  93411. TextureOptimization.prototype.getDescription = function () {
  93412. return "Reducing render target texture size to " + this.maximumSize;
  93413. };
  93414. /**
  93415. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93416. * @param scene defines the current scene where to apply this optimization
  93417. * @param optimizer defines the current optimizer
  93418. * @returns true if everything that can be done was applied
  93419. */
  93420. TextureOptimization.prototype.apply = function (scene, optimizer) {
  93421. var allDone = true;
  93422. for (var index = 0; index < scene.textures.length; index++) {
  93423. var texture = scene.textures[index];
  93424. if (!texture.canRescale || texture.getContext) {
  93425. continue;
  93426. }
  93427. var currentSize = texture.getSize();
  93428. var maxDimension = Math.max(currentSize.width, currentSize.height);
  93429. if (maxDimension > this.maximumSize) {
  93430. texture.scale(this.step);
  93431. allDone = false;
  93432. }
  93433. }
  93434. return allDone;
  93435. };
  93436. return TextureOptimization;
  93437. }(SceneOptimization));
  93438. BABYLON.TextureOptimization = TextureOptimization;
  93439. /**
  93440. * Defines an optimization used to increase or decrease the rendering resolution
  93441. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93442. */
  93443. var HardwareScalingOptimization = /** @class */ (function (_super) {
  93444. __extends(HardwareScalingOptimization, _super);
  93445. /**
  93446. * Creates the HardwareScalingOptimization object
  93447. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  93448. * @param maximumScale defines the maximum scale to use (2 by default)
  93449. * @param step defines the step to use between two passes (0.5 by default)
  93450. */
  93451. function HardwareScalingOptimization(
  93452. /**
  93453. * Defines the priority of this optimization (0 by default which means first in the list)
  93454. */
  93455. priority,
  93456. /**
  93457. * Defines the maximum scale to use (2 by default)
  93458. */
  93459. maximumScale,
  93460. /**
  93461. * Defines the step to use between two passes (0.5 by default)
  93462. */
  93463. step) {
  93464. if (priority === void 0) { priority = 0; }
  93465. if (maximumScale === void 0) { maximumScale = 2; }
  93466. if (step === void 0) { step = 0.25; }
  93467. var _this = _super.call(this, priority) || this;
  93468. _this.priority = priority;
  93469. _this.maximumScale = maximumScale;
  93470. _this.step = step;
  93471. _this._currentScale = -1;
  93472. _this._directionOffset = 1;
  93473. return _this;
  93474. }
  93475. /**
  93476. * Gets a string describing the action executed by the current optimization
  93477. * @return description string
  93478. */
  93479. HardwareScalingOptimization.prototype.getDescription = function () {
  93480. return "Setting hardware scaling level to " + this._currentScale;
  93481. };
  93482. /**
  93483. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93484. * @param scene defines the current scene where to apply this optimization
  93485. * @param optimizer defines the current optimizer
  93486. * @returns true if everything that can be done was applied
  93487. */
  93488. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  93489. if (this._currentScale === -1) {
  93490. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  93491. if (this._currentScale > this.maximumScale) {
  93492. this._directionOffset = -1;
  93493. }
  93494. }
  93495. this._currentScale += this._directionOffset * this.step;
  93496. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  93497. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  93498. };
  93499. ;
  93500. return HardwareScalingOptimization;
  93501. }(SceneOptimization));
  93502. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  93503. /**
  93504. * Defines an optimization used to remove shadows
  93505. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93506. */
  93507. var ShadowsOptimization = /** @class */ (function (_super) {
  93508. __extends(ShadowsOptimization, _super);
  93509. function ShadowsOptimization() {
  93510. return _super !== null && _super.apply(this, arguments) || this;
  93511. }
  93512. /**
  93513. * Gets a string describing the action executed by the current optimization
  93514. * @return description string
  93515. */
  93516. ShadowsOptimization.prototype.getDescription = function () {
  93517. return "Turning shadows on/off";
  93518. };
  93519. /**
  93520. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93521. * @param scene defines the current scene where to apply this optimization
  93522. * @param optimizer defines the current optimizer
  93523. * @returns true if everything that can be done was applied
  93524. */
  93525. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  93526. scene.shadowsEnabled = optimizer.isInImprovementMode;
  93527. return true;
  93528. };
  93529. ;
  93530. return ShadowsOptimization;
  93531. }(SceneOptimization));
  93532. BABYLON.ShadowsOptimization = ShadowsOptimization;
  93533. /**
  93534. * Defines an optimization used to turn post-processes off
  93535. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93536. */
  93537. var PostProcessesOptimization = /** @class */ (function (_super) {
  93538. __extends(PostProcessesOptimization, _super);
  93539. function PostProcessesOptimization() {
  93540. return _super !== null && _super.apply(this, arguments) || this;
  93541. }
  93542. /**
  93543. * Gets a string describing the action executed by the current optimization
  93544. * @return description string
  93545. */
  93546. PostProcessesOptimization.prototype.getDescription = function () {
  93547. return "Turning post-processes on/off";
  93548. };
  93549. /**
  93550. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93551. * @param scene defines the current scene where to apply this optimization
  93552. * @param optimizer defines the current optimizer
  93553. * @returns true if everything that can be done was applied
  93554. */
  93555. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  93556. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  93557. return true;
  93558. };
  93559. ;
  93560. return PostProcessesOptimization;
  93561. }(SceneOptimization));
  93562. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  93563. /**
  93564. * Defines an optimization used to turn lens flares off
  93565. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93566. */
  93567. var LensFlaresOptimization = /** @class */ (function (_super) {
  93568. __extends(LensFlaresOptimization, _super);
  93569. function LensFlaresOptimization() {
  93570. return _super !== null && _super.apply(this, arguments) || this;
  93571. }
  93572. /**
  93573. * Gets a string describing the action executed by the current optimization
  93574. * @return description string
  93575. */
  93576. LensFlaresOptimization.prototype.getDescription = function () {
  93577. return "Turning lens flares on/off";
  93578. };
  93579. /**
  93580. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93581. * @param scene defines the current scene where to apply this optimization
  93582. * @param optimizer defines the current optimizer
  93583. * @returns true if everything that can be done was applied
  93584. */
  93585. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  93586. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  93587. return true;
  93588. };
  93589. ;
  93590. return LensFlaresOptimization;
  93591. }(SceneOptimization));
  93592. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  93593. /**
  93594. * Defines an optimization based on user defined callback.
  93595. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93596. */
  93597. var CustomOptimization = /** @class */ (function (_super) {
  93598. __extends(CustomOptimization, _super);
  93599. function CustomOptimization() {
  93600. return _super !== null && _super.apply(this, arguments) || this;
  93601. }
  93602. /**
  93603. * Gets a string describing the action executed by the current optimization
  93604. * @returns description string
  93605. */
  93606. CustomOptimization.prototype.getDescription = function () {
  93607. if (this.onGetDescription) {
  93608. return this.onGetDescription();
  93609. }
  93610. return "Running user defined callback";
  93611. };
  93612. /**
  93613. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93614. * @param scene defines the current scene where to apply this optimization
  93615. * @param optimizer defines the current optimizer
  93616. * @returns true if everything that can be done was applied
  93617. */
  93618. CustomOptimization.prototype.apply = function (scene, optimizer) {
  93619. if (this.onApply) {
  93620. return this.onApply(scene, optimizer);
  93621. }
  93622. return true;
  93623. };
  93624. ;
  93625. return CustomOptimization;
  93626. }(SceneOptimization));
  93627. BABYLON.CustomOptimization = CustomOptimization;
  93628. /**
  93629. * Defines an optimization used to turn particles off
  93630. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93631. */
  93632. var ParticlesOptimization = /** @class */ (function (_super) {
  93633. __extends(ParticlesOptimization, _super);
  93634. function ParticlesOptimization() {
  93635. return _super !== null && _super.apply(this, arguments) || this;
  93636. }
  93637. /**
  93638. * Gets a string describing the action executed by the current optimization
  93639. * @return description string
  93640. */
  93641. ParticlesOptimization.prototype.getDescription = function () {
  93642. return "Turning particles on/off";
  93643. };
  93644. /**
  93645. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93646. * @param scene defines the current scene where to apply this optimization
  93647. * @param optimizer defines the current optimizer
  93648. * @returns true if everything that can be done was applied
  93649. */
  93650. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  93651. scene.particlesEnabled = optimizer.isInImprovementMode;
  93652. return true;
  93653. };
  93654. ;
  93655. return ParticlesOptimization;
  93656. }(SceneOptimization));
  93657. BABYLON.ParticlesOptimization = ParticlesOptimization;
  93658. /**
  93659. * Defines an optimization used to turn render targets off
  93660. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93661. */
  93662. var RenderTargetsOptimization = /** @class */ (function (_super) {
  93663. __extends(RenderTargetsOptimization, _super);
  93664. function RenderTargetsOptimization() {
  93665. return _super !== null && _super.apply(this, arguments) || this;
  93666. }
  93667. /**
  93668. * Gets a string describing the action executed by the current optimization
  93669. * @return description string
  93670. */
  93671. RenderTargetsOptimization.prototype.getDescription = function () {
  93672. return "Turning render targets off";
  93673. };
  93674. /**
  93675. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93676. * @param scene defines the current scene where to apply this optimization
  93677. * @param optimizer defines the current optimizer
  93678. * @returns true if everything that can be done was applied
  93679. */
  93680. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  93681. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  93682. return true;
  93683. };
  93684. ;
  93685. return RenderTargetsOptimization;
  93686. }(SceneOptimization));
  93687. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  93688. /**
  93689. * Defines an optimization used to merge meshes with compatible materials
  93690. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93691. */
  93692. var MergeMeshesOptimization = /** @class */ (function (_super) {
  93693. __extends(MergeMeshesOptimization, _super);
  93694. function MergeMeshesOptimization() {
  93695. var _this = _super !== null && _super.apply(this, arguments) || this;
  93696. _this._canBeMerged = function (abstractMesh) {
  93697. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  93698. return false;
  93699. }
  93700. var mesh = abstractMesh;
  93701. if (!mesh.isVisible || !mesh.isEnabled()) {
  93702. return false;
  93703. }
  93704. if (mesh.instances.length > 0) {
  93705. return false;
  93706. }
  93707. if (mesh.skeleton || mesh.hasLODLevels) {
  93708. return false;
  93709. }
  93710. if (mesh.parent) {
  93711. return false;
  93712. }
  93713. return true;
  93714. };
  93715. return _this;
  93716. }
  93717. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  93718. /**
  93719. * Gets or sets a boolean which defines if optimization octree has to be updated
  93720. */
  93721. get: function () {
  93722. return MergeMeshesOptimization._UpdateSelectionTree;
  93723. },
  93724. /**
  93725. * Gets or sets a boolean which defines if optimization octree has to be updated
  93726. */
  93727. set: function (value) {
  93728. MergeMeshesOptimization._UpdateSelectionTree = value;
  93729. },
  93730. enumerable: true,
  93731. configurable: true
  93732. });
  93733. /**
  93734. * Gets a string describing the action executed by the current optimization
  93735. * @return description string
  93736. */
  93737. MergeMeshesOptimization.prototype.getDescription = function () {
  93738. return "Merging similar meshes together";
  93739. };
  93740. /**
  93741. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93742. * @param scene defines the current scene where to apply this optimization
  93743. * @param optimizer defines the current optimizer
  93744. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  93745. * @returns true if everything that can be done was applied
  93746. */
  93747. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  93748. var globalPool = scene.meshes.slice(0);
  93749. var globalLength = globalPool.length;
  93750. for (var index = 0; index < globalLength; index++) {
  93751. var currentPool = new Array();
  93752. var current = globalPool[index];
  93753. // Checks
  93754. if (!this._canBeMerged(current)) {
  93755. continue;
  93756. }
  93757. currentPool.push(current);
  93758. // Find compatible meshes
  93759. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  93760. var otherMesh = globalPool[subIndex];
  93761. if (!this._canBeMerged(otherMesh)) {
  93762. continue;
  93763. }
  93764. if (otherMesh.material !== current.material) {
  93765. continue;
  93766. }
  93767. if (otherMesh.checkCollisions !== current.checkCollisions) {
  93768. continue;
  93769. }
  93770. currentPool.push(otherMesh);
  93771. globalLength--;
  93772. globalPool.splice(subIndex, 1);
  93773. subIndex--;
  93774. }
  93775. if (currentPool.length < 2) {
  93776. continue;
  93777. }
  93778. // Merge meshes
  93779. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  93780. }
  93781. if (updateSelectionTree != undefined) {
  93782. if (updateSelectionTree) {
  93783. scene.createOrUpdateSelectionOctree();
  93784. }
  93785. }
  93786. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  93787. scene.createOrUpdateSelectionOctree();
  93788. }
  93789. return true;
  93790. };
  93791. ;
  93792. MergeMeshesOptimization._UpdateSelectionTree = false;
  93793. return MergeMeshesOptimization;
  93794. }(SceneOptimization));
  93795. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  93796. /**
  93797. * Defines a list of options used by SceneOptimizer
  93798. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93799. */
  93800. var SceneOptimizerOptions = /** @class */ (function () {
  93801. /**
  93802. * Creates a new list of options used by SceneOptimizer
  93803. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  93804. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  93805. */
  93806. function SceneOptimizerOptions(
  93807. /**
  93808. * Defines the target frame rate to reach (60 by default)
  93809. */
  93810. targetFrameRate,
  93811. /**
  93812. * Defines the interval between two checkes (2000ms by default)
  93813. */
  93814. trackerDuration) {
  93815. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  93816. if (trackerDuration === void 0) { trackerDuration = 2000; }
  93817. this.targetFrameRate = targetFrameRate;
  93818. this.trackerDuration = trackerDuration;
  93819. /**
  93820. * Gets the list of optimizations to apply
  93821. */
  93822. this.optimizations = new Array();
  93823. }
  93824. /**
  93825. * Add a new optimization
  93826. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  93827. * @returns the current SceneOptimizerOptions
  93828. */
  93829. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  93830. this.optimizations.push(optimization);
  93831. return this;
  93832. };
  93833. /**
  93834. * Add a new custom optimization
  93835. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  93836. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  93837. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  93838. * @returns the current SceneOptimizerOptions
  93839. */
  93840. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  93841. if (priority === void 0) { priority = 0; }
  93842. var optimization = new CustomOptimization(priority);
  93843. optimization.onApply = onApply;
  93844. optimization.onGetDescription = onGetDescription;
  93845. this.optimizations.push(optimization);
  93846. return this;
  93847. };
  93848. /**
  93849. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  93850. * @param targetFrameRate defines the target frame rate (60 by default)
  93851. * @returns a SceneOptimizerOptions object
  93852. */
  93853. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  93854. var result = new SceneOptimizerOptions(targetFrameRate);
  93855. var priority = 0;
  93856. result.addOptimization(new MergeMeshesOptimization(priority));
  93857. result.addOptimization(new ShadowsOptimization(priority));
  93858. result.addOptimization(new LensFlaresOptimization(priority));
  93859. // Next priority
  93860. priority++;
  93861. result.addOptimization(new PostProcessesOptimization(priority));
  93862. result.addOptimization(new ParticlesOptimization(priority));
  93863. // Next priority
  93864. priority++;
  93865. result.addOptimization(new TextureOptimization(priority, 1024));
  93866. return result;
  93867. };
  93868. /**
  93869. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  93870. * @param targetFrameRate defines the target frame rate (60 by default)
  93871. * @returns a SceneOptimizerOptions object
  93872. */
  93873. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  93874. var result = new SceneOptimizerOptions(targetFrameRate);
  93875. var priority = 0;
  93876. result.addOptimization(new MergeMeshesOptimization(priority));
  93877. result.addOptimization(new ShadowsOptimization(priority));
  93878. result.addOptimization(new LensFlaresOptimization(priority));
  93879. // Next priority
  93880. priority++;
  93881. result.addOptimization(new PostProcessesOptimization(priority));
  93882. result.addOptimization(new ParticlesOptimization(priority));
  93883. // Next priority
  93884. priority++;
  93885. result.addOptimization(new TextureOptimization(priority, 512));
  93886. // Next priority
  93887. priority++;
  93888. result.addOptimization(new RenderTargetsOptimization(priority));
  93889. // Next priority
  93890. priority++;
  93891. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  93892. return result;
  93893. };
  93894. /**
  93895. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  93896. * @param targetFrameRate defines the target frame rate (60 by default)
  93897. * @returns a SceneOptimizerOptions object
  93898. */
  93899. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  93900. var result = new SceneOptimizerOptions(targetFrameRate);
  93901. var priority = 0;
  93902. result.addOptimization(new MergeMeshesOptimization(priority));
  93903. result.addOptimization(new ShadowsOptimization(priority));
  93904. result.addOptimization(new LensFlaresOptimization(priority));
  93905. // Next priority
  93906. priority++;
  93907. result.addOptimization(new PostProcessesOptimization(priority));
  93908. result.addOptimization(new ParticlesOptimization(priority));
  93909. // Next priority
  93910. priority++;
  93911. result.addOptimization(new TextureOptimization(priority, 256));
  93912. // Next priority
  93913. priority++;
  93914. result.addOptimization(new RenderTargetsOptimization(priority));
  93915. // Next priority
  93916. priority++;
  93917. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  93918. return result;
  93919. };
  93920. return SceneOptimizerOptions;
  93921. }());
  93922. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  93923. /**
  93924. * Class used to run optimizations in order to reach a target frame rate
  93925. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93926. */
  93927. var SceneOptimizer = /** @class */ (function () {
  93928. /**
  93929. * Creates a new SceneOptimizer
  93930. * @param scene defines the scene to work on
  93931. * @param options defines the options to use with the SceneOptimizer
  93932. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  93933. * @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)
  93934. */
  93935. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  93936. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  93937. if (improvementMode === void 0) { improvementMode = false; }
  93938. var _this = this;
  93939. this._isRunning = false;
  93940. this._currentPriorityLevel = 0;
  93941. this._targetFrameRate = 60;
  93942. this._trackerDuration = 2000;
  93943. this._currentFrameRate = 0;
  93944. this._improvementMode = false;
  93945. /**
  93946. * Defines an observable called when the optimizer reaches the target frame rate
  93947. */
  93948. this.onSuccessObservable = new BABYLON.Observable();
  93949. /**
  93950. * Defines an observable called when the optimizer enables an optimization
  93951. */
  93952. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  93953. /**
  93954. * Defines an observable called when the optimizer is not able to reach the target frame rate
  93955. */
  93956. this.onFailureObservable = new BABYLON.Observable();
  93957. if (!options) {
  93958. this._options = new SceneOptimizerOptions();
  93959. }
  93960. else {
  93961. this._options = options;
  93962. }
  93963. if (this._options.targetFrameRate) {
  93964. this._targetFrameRate = this._options.targetFrameRate;
  93965. }
  93966. if (this._options.trackerDuration) {
  93967. this._trackerDuration = this._options.trackerDuration;
  93968. }
  93969. if (autoGeneratePriorities) {
  93970. var priority = 0;
  93971. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  93972. var optim = _a[_i];
  93973. optim.priority = priority++;
  93974. }
  93975. }
  93976. this._improvementMode = improvementMode;
  93977. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  93978. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  93979. _this._sceneDisposeObserver = null;
  93980. _this.dispose();
  93981. });
  93982. }
  93983. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  93984. /**
  93985. * Gets a boolean indicating if the optimizer is in improvement mode
  93986. */
  93987. get: function () {
  93988. return this._improvementMode;
  93989. },
  93990. enumerable: true,
  93991. configurable: true
  93992. });
  93993. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  93994. /**
  93995. * Gets the current priority level (0 at start)
  93996. */
  93997. get: function () {
  93998. return this._currentPriorityLevel;
  93999. },
  94000. enumerable: true,
  94001. configurable: true
  94002. });
  94003. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  94004. /**
  94005. * Gets the current frame rate checked by the SceneOptimizer
  94006. */
  94007. get: function () {
  94008. return this._currentFrameRate;
  94009. },
  94010. enumerable: true,
  94011. configurable: true
  94012. });
  94013. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  94014. /**
  94015. * Gets or sets the current target frame rate (60 by default)
  94016. */
  94017. get: function () {
  94018. return this._targetFrameRate;
  94019. },
  94020. /**
  94021. * Gets or sets the current target frame rate (60 by default)
  94022. */
  94023. set: function (value) {
  94024. this._targetFrameRate = value;
  94025. },
  94026. enumerable: true,
  94027. configurable: true
  94028. });
  94029. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  94030. /**
  94031. * Gets or sets the current interval between two checks (every 2000ms by default)
  94032. */
  94033. get: function () {
  94034. return this._trackerDuration;
  94035. },
  94036. /**
  94037. * Gets or sets the current interval between two checks (every 2000ms by default)
  94038. */
  94039. set: function (value) {
  94040. this._trackerDuration = value;
  94041. },
  94042. enumerable: true,
  94043. configurable: true
  94044. });
  94045. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  94046. /**
  94047. * Gets the list of active optimizations
  94048. */
  94049. get: function () {
  94050. return this._options.optimizations;
  94051. },
  94052. enumerable: true,
  94053. configurable: true
  94054. });
  94055. /**
  94056. * Stops the current optimizer
  94057. */
  94058. SceneOptimizer.prototype.stop = function () {
  94059. this._isRunning = false;
  94060. };
  94061. /**
  94062. * Reset the optimizer to initial step (current priority level = 0)
  94063. */
  94064. SceneOptimizer.prototype.reset = function () {
  94065. this._currentPriorityLevel = 0;
  94066. };
  94067. /**
  94068. * Start the optimizer. By default it will try to reach a specific framerate
  94069. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  94070. */
  94071. SceneOptimizer.prototype.start = function () {
  94072. var _this = this;
  94073. if (this._isRunning) {
  94074. return;
  94075. }
  94076. this._isRunning = true;
  94077. // Let's wait for the scene to be ready before running our check
  94078. this._scene.executeWhenReady(function () {
  94079. setTimeout(function () {
  94080. _this._checkCurrentState();
  94081. }, _this._trackerDuration);
  94082. });
  94083. };
  94084. SceneOptimizer.prototype._checkCurrentState = function () {
  94085. var _this = this;
  94086. if (!this._isRunning) {
  94087. return;
  94088. }
  94089. var scene = this._scene;
  94090. var options = this._options;
  94091. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  94092. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  94093. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  94094. this._isRunning = false;
  94095. this.onSuccessObservable.notifyObservers(this);
  94096. return;
  94097. }
  94098. // Apply current level of optimizations
  94099. var allDone = true;
  94100. var noOptimizationApplied = true;
  94101. for (var index = 0; index < options.optimizations.length; index++) {
  94102. var optimization = options.optimizations[index];
  94103. if (optimization.priority === this._currentPriorityLevel) {
  94104. noOptimizationApplied = false;
  94105. allDone = allDone && optimization.apply(scene, this);
  94106. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  94107. }
  94108. }
  94109. // If no optimization was applied, this is a failure :(
  94110. if (noOptimizationApplied) {
  94111. this._isRunning = false;
  94112. this.onFailureObservable.notifyObservers(this);
  94113. return;
  94114. }
  94115. // If all optimizations were done, move to next level
  94116. if (allDone) {
  94117. this._currentPriorityLevel++;
  94118. }
  94119. // Let's the system running for a specific amount of time before checking FPS
  94120. scene.executeWhenReady(function () {
  94121. setTimeout(function () {
  94122. _this._checkCurrentState();
  94123. }, _this._trackerDuration);
  94124. });
  94125. };
  94126. /**
  94127. * Release all resources
  94128. */
  94129. SceneOptimizer.prototype.dispose = function () {
  94130. this.stop();
  94131. this.onSuccessObservable.clear();
  94132. this.onFailureObservable.clear();
  94133. this.onNewOptimizationAppliedObservable.clear();
  94134. if (this._sceneDisposeObserver) {
  94135. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  94136. }
  94137. };
  94138. /**
  94139. * Helper function to create a SceneOptimizer with one single line of code
  94140. * @param scene defines the scene to work on
  94141. * @param options defines the options to use with the SceneOptimizer
  94142. * @param onSuccess defines a callback to call on success
  94143. * @param onFailure defines a callback to call on failure
  94144. * @returns the new SceneOptimizer object
  94145. */
  94146. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  94147. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  94148. if (onSuccess) {
  94149. optimizer.onSuccessObservable.add(function () {
  94150. onSuccess();
  94151. });
  94152. }
  94153. if (onFailure) {
  94154. optimizer.onFailureObservable.add(function () {
  94155. onFailure();
  94156. });
  94157. }
  94158. optimizer.start();
  94159. return optimizer;
  94160. };
  94161. return SceneOptimizer;
  94162. }());
  94163. BABYLON.SceneOptimizer = SceneOptimizer;
  94164. })(BABYLON || (BABYLON = {}));
  94165. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  94166. var BABYLON;
  94167. (function (BABYLON) {
  94168. var OutlineRenderer = /** @class */ (function () {
  94169. function OutlineRenderer(scene) {
  94170. this.zOffset = 1;
  94171. this._scene = scene;
  94172. }
  94173. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  94174. var _this = this;
  94175. if (useOverlay === void 0) { useOverlay = false; }
  94176. var scene = this._scene;
  94177. var engine = this._scene.getEngine();
  94178. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  94179. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  94180. return;
  94181. }
  94182. var mesh = subMesh.getRenderingMesh();
  94183. var material = subMesh.getMaterial();
  94184. if (!material || !scene.activeCamera) {
  94185. return;
  94186. }
  94187. engine.enableEffect(this._effect);
  94188. // Logarithmic depth
  94189. if (material.useLogarithmicDepth) {
  94190. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  94191. }
  94192. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  94193. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  94194. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  94195. // Bones
  94196. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  94197. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  94198. }
  94199. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  94200. // Alpha test
  94201. if (material && material.needAlphaTesting()) {
  94202. var alphaTexture = material.getAlphaTestTexture();
  94203. if (alphaTexture) {
  94204. this._effect.setTexture("diffuseSampler", alphaTexture);
  94205. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  94206. }
  94207. }
  94208. engine.setZOffset(-this.zOffset);
  94209. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  94210. engine.setZOffset(0);
  94211. };
  94212. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  94213. var defines = [];
  94214. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  94215. var mesh = subMesh.getMesh();
  94216. var material = subMesh.getMaterial();
  94217. if (material) {
  94218. // Alpha test
  94219. if (material.needAlphaTesting()) {
  94220. defines.push("#define ALPHATEST");
  94221. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  94222. attribs.push(BABYLON.VertexBuffer.UVKind);
  94223. defines.push("#define UV1");
  94224. }
  94225. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  94226. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  94227. defines.push("#define UV2");
  94228. }
  94229. }
  94230. //Logarithmic depth
  94231. if (material.useLogarithmicDepth) {
  94232. defines.push("#define LOGARITHMICDEPTH");
  94233. }
  94234. }
  94235. // Bones
  94236. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  94237. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  94238. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  94239. if (mesh.numBoneInfluencers > 4) {
  94240. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  94241. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  94242. }
  94243. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  94244. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  94245. }
  94246. else {
  94247. defines.push("#define NUM_BONE_INFLUENCERS 0");
  94248. }
  94249. // Instances
  94250. if (useInstances) {
  94251. defines.push("#define INSTANCES");
  94252. attribs.push("world0");
  94253. attribs.push("world1");
  94254. attribs.push("world2");
  94255. attribs.push("world3");
  94256. }
  94257. // Get correct effect
  94258. var join = defines.join("\n");
  94259. if (this._cachedDefines !== join) {
  94260. this._cachedDefines = join;
  94261. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  94262. }
  94263. return this._effect.isReady();
  94264. };
  94265. return OutlineRenderer;
  94266. }());
  94267. BABYLON.OutlineRenderer = OutlineRenderer;
  94268. })(BABYLON || (BABYLON = {}));
  94269. //# sourceMappingURL=babylon.outlineRenderer.js.map
  94270. var BABYLON;
  94271. (function (BABYLON) {
  94272. var FaceAdjacencies = /** @class */ (function () {
  94273. function FaceAdjacencies() {
  94274. this.edges = new Array();
  94275. this.edgesConnectedCount = 0;
  94276. }
  94277. return FaceAdjacencies;
  94278. }());
  94279. var EdgesRenderer = /** @class */ (function () {
  94280. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  94281. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  94282. if (epsilon === void 0) { epsilon = 0.95; }
  94283. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  94284. this.edgesWidthScalerForOrthographic = 1000.0;
  94285. this.edgesWidthScalerForPerspective = 50.0;
  94286. this._linesPositions = new Array();
  94287. this._linesNormals = new Array();
  94288. this._linesIndices = new Array();
  94289. this._buffers = {};
  94290. this._checkVerticesInsteadOfIndices = false;
  94291. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  94292. this.isEnabled = true;
  94293. this._source = source;
  94294. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  94295. this._epsilon = epsilon;
  94296. this._prepareRessources();
  94297. this._generateEdgesLines();
  94298. }
  94299. EdgesRenderer.prototype._prepareRessources = function () {
  94300. if (this._lineShader) {
  94301. return;
  94302. }
  94303. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  94304. attributes: ["position", "normal"],
  94305. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  94306. });
  94307. this._lineShader.disableDepthWrite = true;
  94308. this._lineShader.backFaceCulling = false;
  94309. };
  94310. EdgesRenderer.prototype._rebuild = function () {
  94311. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  94312. if (buffer) {
  94313. buffer._rebuild();
  94314. }
  94315. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  94316. if (buffer) {
  94317. buffer._rebuild();
  94318. }
  94319. var scene = this._source.getScene();
  94320. var engine = scene.getEngine();
  94321. this._ib = engine.createIndexBuffer(this._linesIndices);
  94322. };
  94323. EdgesRenderer.prototype.dispose = function () {
  94324. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  94325. if (buffer) {
  94326. buffer.dispose();
  94327. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  94328. }
  94329. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  94330. if (buffer) {
  94331. buffer.dispose();
  94332. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  94333. }
  94334. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  94335. this._lineShader.dispose();
  94336. };
  94337. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  94338. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  94339. return 0;
  94340. }
  94341. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  94342. return 1;
  94343. }
  94344. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  94345. return 2;
  94346. }
  94347. return -1;
  94348. };
  94349. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  94350. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  94351. return 0;
  94352. }
  94353. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  94354. return 1;
  94355. }
  94356. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  94357. return 2;
  94358. }
  94359. return -1;
  94360. };
  94361. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  94362. var needToCreateLine;
  94363. if (edge === undefined) {
  94364. needToCreateLine = true;
  94365. }
  94366. else {
  94367. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  94368. needToCreateLine = dotProduct < this._epsilon;
  94369. }
  94370. if (needToCreateLine) {
  94371. var offset = this._linesPositions.length / 3;
  94372. var normal = p0.subtract(p1);
  94373. normal.normalize();
  94374. // Positions
  94375. this._linesPositions.push(p0.x);
  94376. this._linesPositions.push(p0.y);
  94377. this._linesPositions.push(p0.z);
  94378. this._linesPositions.push(p0.x);
  94379. this._linesPositions.push(p0.y);
  94380. this._linesPositions.push(p0.z);
  94381. this._linesPositions.push(p1.x);
  94382. this._linesPositions.push(p1.y);
  94383. this._linesPositions.push(p1.z);
  94384. this._linesPositions.push(p1.x);
  94385. this._linesPositions.push(p1.y);
  94386. this._linesPositions.push(p1.z);
  94387. // Normals
  94388. this._linesNormals.push(p1.x);
  94389. this._linesNormals.push(p1.y);
  94390. this._linesNormals.push(p1.z);
  94391. this._linesNormals.push(-1);
  94392. this._linesNormals.push(p1.x);
  94393. this._linesNormals.push(p1.y);
  94394. this._linesNormals.push(p1.z);
  94395. this._linesNormals.push(1);
  94396. this._linesNormals.push(p0.x);
  94397. this._linesNormals.push(p0.y);
  94398. this._linesNormals.push(p0.z);
  94399. this._linesNormals.push(-1);
  94400. this._linesNormals.push(p0.x);
  94401. this._linesNormals.push(p0.y);
  94402. this._linesNormals.push(p0.z);
  94403. this._linesNormals.push(1);
  94404. // Indices
  94405. this._linesIndices.push(offset);
  94406. this._linesIndices.push(offset + 1);
  94407. this._linesIndices.push(offset + 2);
  94408. this._linesIndices.push(offset);
  94409. this._linesIndices.push(offset + 2);
  94410. this._linesIndices.push(offset + 3);
  94411. }
  94412. };
  94413. EdgesRenderer.prototype._generateEdgesLines = function () {
  94414. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  94415. var indices = this._source.getIndices();
  94416. if (!indices || !positions) {
  94417. return;
  94418. }
  94419. // First let's find adjacencies
  94420. var adjacencies = new Array();
  94421. var faceNormals = new Array();
  94422. var index;
  94423. var faceAdjacencies;
  94424. // Prepare faces
  94425. for (index = 0; index < indices.length; index += 3) {
  94426. faceAdjacencies = new FaceAdjacencies();
  94427. var p0Index = indices[index];
  94428. var p1Index = indices[index + 1];
  94429. var p2Index = indices[index + 2];
  94430. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  94431. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  94432. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  94433. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  94434. faceNormal.normalize();
  94435. faceNormals.push(faceNormal);
  94436. adjacencies.push(faceAdjacencies);
  94437. }
  94438. // Scan
  94439. for (index = 0; index < adjacencies.length; index++) {
  94440. faceAdjacencies = adjacencies[index];
  94441. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  94442. var otherFaceAdjacencies = adjacencies[otherIndex];
  94443. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  94444. break;
  94445. }
  94446. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  94447. continue;
  94448. }
  94449. var otherP0 = indices[otherIndex * 3];
  94450. var otherP1 = indices[otherIndex * 3 + 1];
  94451. var otherP2 = indices[otherIndex * 3 + 2];
  94452. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  94453. var otherEdgeIndex = 0;
  94454. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  94455. continue;
  94456. }
  94457. switch (edgeIndex) {
  94458. case 0:
  94459. if (this._checkVerticesInsteadOfIndices) {
  94460. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  94461. }
  94462. else {
  94463. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  94464. }
  94465. break;
  94466. case 1:
  94467. if (this._checkVerticesInsteadOfIndices) {
  94468. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  94469. }
  94470. else {
  94471. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  94472. }
  94473. break;
  94474. case 2:
  94475. if (this._checkVerticesInsteadOfIndices) {
  94476. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  94477. }
  94478. else {
  94479. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  94480. }
  94481. break;
  94482. }
  94483. if (otherEdgeIndex === -1) {
  94484. continue;
  94485. }
  94486. faceAdjacencies.edges[edgeIndex] = otherIndex;
  94487. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  94488. faceAdjacencies.edgesConnectedCount++;
  94489. otherFaceAdjacencies.edgesConnectedCount++;
  94490. if (faceAdjacencies.edgesConnectedCount === 3) {
  94491. break;
  94492. }
  94493. }
  94494. }
  94495. }
  94496. // Create lines
  94497. for (index = 0; index < adjacencies.length; index++) {
  94498. // 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
  94499. var current = adjacencies[index];
  94500. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  94501. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  94502. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  94503. }
  94504. // Merge into a single mesh
  94505. var engine = this._source.getScene().getEngine();
  94506. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  94507. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  94508. this._ib = engine.createIndexBuffer(this._linesIndices);
  94509. this._indicesCount = this._linesIndices.length;
  94510. };
  94511. EdgesRenderer.prototype.render = function () {
  94512. var scene = this._source.getScene();
  94513. if (!this._lineShader.isReady() || !scene.activeCamera) {
  94514. return;
  94515. }
  94516. var engine = scene.getEngine();
  94517. this._lineShader._preBind();
  94518. // VBOs
  94519. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  94520. scene.resetCachedMaterial();
  94521. this._lineShader.setColor4("color", this._source.edgesColor);
  94522. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  94523. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  94524. }
  94525. else {
  94526. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  94527. }
  94528. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  94529. this._lineShader.bind(this._source.getWorldMatrix());
  94530. // Draw order
  94531. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  94532. this._lineShader.unbind();
  94533. engine.setDepthWrite(true);
  94534. };
  94535. return EdgesRenderer;
  94536. }());
  94537. BABYLON.EdgesRenderer = EdgesRenderer;
  94538. })(BABYLON || (BABYLON = {}));
  94539. //# sourceMappingURL=babylon.edgesRenderer.js.map
  94540. var __assign = (this && this.__assign) || Object.assign || function(t) {
  94541. for (var s, i = 1, n = arguments.length; i < n; i++) {
  94542. s = arguments[i];
  94543. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  94544. t[p] = s[p];
  94545. }
  94546. return t;
  94547. };
  94548. var BABYLON;
  94549. (function (BABYLON) {
  94550. /**
  94551. * The effect layer Helps adding post process effect blended with the main pass.
  94552. *
  94553. * This can be for instance use to generate glow or higlight effects on the scene.
  94554. *
  94555. * The effect layer class can not be used directly and is intented to inherited from to be
  94556. * customized per effects.
  94557. */
  94558. var EffectLayer = /** @class */ (function () {
  94559. /**
  94560. * Instantiates a new effect Layer and references it in the scene.
  94561. * @param name The name of the layer
  94562. * @param scene The scene to use the layer in
  94563. */
  94564. function EffectLayer(
  94565. /** The Friendly of the effect in the scene */
  94566. name, scene) {
  94567. this._vertexBuffers = {};
  94568. this._maxSize = 0;
  94569. this._mainTextureDesiredSize = { width: 0, height: 0 };
  94570. this._shouldRender = true;
  94571. this._postProcesses = [];
  94572. this._textures = [];
  94573. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  94574. /**
  94575. * The clear color of the texture used to generate the glow map.
  94576. */
  94577. this.neutralColor = new BABYLON.Color4();
  94578. /**
  94579. * Specifies wether the highlight layer is enabled or not.
  94580. */
  94581. this.isEnabled = true;
  94582. /**
  94583. * An event triggered when the effect layer has been disposed.
  94584. */
  94585. this.onDisposeObservable = new BABYLON.Observable();
  94586. /**
  94587. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  94588. */
  94589. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  94590. /**
  94591. * An event triggered when the generated texture is being merged in the scene.
  94592. */
  94593. this.onBeforeComposeObservable = new BABYLON.Observable();
  94594. /**
  94595. * An event triggered when the generated texture has been merged in the scene.
  94596. */
  94597. this.onAfterComposeObservable = new BABYLON.Observable();
  94598. /**
  94599. * An event triggered when the efffect layer changes its size.
  94600. */
  94601. this.onSizeChangedObservable = new BABYLON.Observable();
  94602. this.name = name;
  94603. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  94604. this._engine = scene.getEngine();
  94605. this._maxSize = this._engine.getCaps().maxTextureSize;
  94606. this._scene.effectLayers.push(this);
  94607. // Generate Buffers
  94608. this._generateIndexBuffer();
  94609. this._genrateVertexBuffer();
  94610. }
  94611. Object.defineProperty(EffectLayer.prototype, "camera", {
  94612. /**
  94613. * Gets the camera attached to the layer.
  94614. */
  94615. get: function () {
  94616. return this._effectLayerOptions.camera;
  94617. },
  94618. enumerable: true,
  94619. configurable: true
  94620. });
  94621. /**
  94622. * Initializes the effect layer with the required options.
  94623. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  94624. */
  94625. EffectLayer.prototype._init = function (options) {
  94626. // Adapt options
  94627. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  94628. this._setMainTextureSize();
  94629. this._createMainTexture();
  94630. this._createTextureAndPostProcesses();
  94631. this._mergeEffect = this._createMergeEffect();
  94632. };
  94633. /**
  94634. * Generates the index buffer of the full screen quad blending to the main canvas.
  94635. */
  94636. EffectLayer.prototype._generateIndexBuffer = function () {
  94637. // Indices
  94638. var indices = [];
  94639. indices.push(0);
  94640. indices.push(1);
  94641. indices.push(2);
  94642. indices.push(0);
  94643. indices.push(2);
  94644. indices.push(3);
  94645. this._indexBuffer = this._engine.createIndexBuffer(indices);
  94646. };
  94647. /**
  94648. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  94649. */
  94650. EffectLayer.prototype._genrateVertexBuffer = function () {
  94651. // VBO
  94652. var vertices = [];
  94653. vertices.push(1, 1);
  94654. vertices.push(-1, 1);
  94655. vertices.push(-1, -1);
  94656. vertices.push(1, -1);
  94657. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  94658. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  94659. };
  94660. /**
  94661. * Sets the main texture desired size which is the closest power of two
  94662. * of the engine canvas size.
  94663. */
  94664. EffectLayer.prototype._setMainTextureSize = function () {
  94665. if (this._effectLayerOptions.mainTextureFixedSize) {
  94666. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  94667. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  94668. }
  94669. else {
  94670. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  94671. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  94672. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  94673. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  94674. }
  94675. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  94676. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  94677. };
  94678. /**
  94679. * Creates the main texture for the effect layer.
  94680. */
  94681. EffectLayer.prototype._createMainTexture = function () {
  94682. var _this = this;
  94683. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  94684. width: this._mainTextureDesiredSize.width,
  94685. height: this._mainTextureDesiredSize.height
  94686. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  94687. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  94688. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94689. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94690. this._mainTexture.anisotropicFilteringLevel = 1;
  94691. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94692. this._mainTexture.renderParticles = false;
  94693. this._mainTexture.renderList = null;
  94694. this._mainTexture.ignoreCameraViewport = true;
  94695. // Custom render function
  94696. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  94697. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  94698. var index;
  94699. var engine = _this._scene.getEngine();
  94700. if (depthOnlySubMeshes.length) {
  94701. engine.setColorWrite(false);
  94702. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  94703. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  94704. }
  94705. engine.setColorWrite(true);
  94706. }
  94707. for (index = 0; index < opaqueSubMeshes.length; index++) {
  94708. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  94709. }
  94710. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  94711. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  94712. }
  94713. for (index = 0; index < transparentSubMeshes.length; index++) {
  94714. _this._renderSubMesh(transparentSubMeshes.data[index]);
  94715. }
  94716. };
  94717. this._mainTexture.onClearObservable.add(function (engine) {
  94718. engine.clear(_this.neutralColor, true, true, true);
  94719. });
  94720. };
  94721. /**
  94722. * Checks for the readiness of the element composing the layer.
  94723. * @param subMesh the mesh to check for
  94724. * @param useInstances specify wether or not to use instances to render the mesh
  94725. * @param emissiveTexture the associated emissive texture used to generate the glow
  94726. * @return true if ready otherwise, false
  94727. */
  94728. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  94729. var material = subMesh.getMaterial();
  94730. if (!material) {
  94731. return false;
  94732. }
  94733. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  94734. return false;
  94735. }
  94736. var defines = [];
  94737. var attribs = [BABYLON.VertexBuffer.PositionKind];
  94738. var mesh = subMesh.getMesh();
  94739. var uv1 = false;
  94740. var uv2 = false;
  94741. // Alpha test
  94742. if (material && material.needAlphaTesting()) {
  94743. var alphaTexture = material.getAlphaTestTexture();
  94744. if (alphaTexture) {
  94745. defines.push("#define ALPHATEST");
  94746. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  94747. alphaTexture.coordinatesIndex === 1) {
  94748. defines.push("#define DIFFUSEUV2");
  94749. uv2 = true;
  94750. }
  94751. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  94752. defines.push("#define DIFFUSEUV1");
  94753. uv1 = true;
  94754. }
  94755. }
  94756. }
  94757. // Emissive
  94758. if (emissiveTexture) {
  94759. defines.push("#define EMISSIVE");
  94760. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  94761. emissiveTexture.coordinatesIndex === 1) {
  94762. defines.push("#define EMISSIVEUV2");
  94763. uv2 = true;
  94764. }
  94765. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  94766. defines.push("#define EMISSIVEUV1");
  94767. uv1 = true;
  94768. }
  94769. }
  94770. if (uv1) {
  94771. attribs.push(BABYLON.VertexBuffer.UVKind);
  94772. defines.push("#define UV1");
  94773. }
  94774. if (uv2) {
  94775. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  94776. defines.push("#define UV2");
  94777. }
  94778. // Bones
  94779. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  94780. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  94781. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  94782. if (mesh.numBoneInfluencers > 4) {
  94783. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  94784. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  94785. }
  94786. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  94787. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  94788. }
  94789. else {
  94790. defines.push("#define NUM_BONE_INFLUENCERS 0");
  94791. }
  94792. // Morph targets
  94793. var manager = mesh.morphTargetManager;
  94794. var morphInfluencers = 0;
  94795. if (manager) {
  94796. if (manager.numInfluencers > 0) {
  94797. defines.push("#define MORPHTARGETS");
  94798. morphInfluencers = manager.numInfluencers;
  94799. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  94800. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  94801. }
  94802. }
  94803. // Instances
  94804. if (useInstances) {
  94805. defines.push("#define INSTANCES");
  94806. attribs.push("world0");
  94807. attribs.push("world1");
  94808. attribs.push("world2");
  94809. attribs.push("world3");
  94810. }
  94811. // Get correct effect
  94812. var join = defines.join("\n");
  94813. if (this._cachedDefines !== join) {
  94814. this._cachedDefines = join;
  94815. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  94816. }
  94817. return this._effectLayerMapGenerationEffect.isReady();
  94818. };
  94819. /**
  94820. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  94821. */
  94822. EffectLayer.prototype.render = function () {
  94823. var currentEffect = this._mergeEffect;
  94824. // Check
  94825. if (!currentEffect.isReady())
  94826. return;
  94827. for (var i = 0; i < this._postProcesses.length; i++) {
  94828. if (!this._postProcesses[i].isReady()) {
  94829. return;
  94830. }
  94831. }
  94832. var engine = this._scene.getEngine();
  94833. this.onBeforeComposeObservable.notifyObservers(this);
  94834. // Render
  94835. engine.enableEffect(currentEffect);
  94836. engine.setState(false);
  94837. // VBOs
  94838. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  94839. // Cache
  94840. var previousAlphaMode = engine.getAlphaMode();
  94841. // Go Blend.
  94842. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  94843. // Blends the map on the main canvas.
  94844. this._internalRender(currentEffect);
  94845. // Restore Alpha
  94846. engine.setAlphaMode(previousAlphaMode);
  94847. this.onAfterComposeObservable.notifyObservers(this);
  94848. // Handle size changes.
  94849. var size = this._mainTexture.getSize();
  94850. this._setMainTextureSize();
  94851. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  94852. // Recreate RTT and post processes on size change.
  94853. this.onSizeChangedObservable.notifyObservers(this);
  94854. this._disposeTextureAndPostProcesses();
  94855. this._createMainTexture();
  94856. this._createTextureAndPostProcesses();
  94857. }
  94858. };
  94859. /**
  94860. * Determine if a given mesh will be used in the current effect.
  94861. * @param mesh mesh to test
  94862. * @returns true if the mesh will be used
  94863. */
  94864. EffectLayer.prototype.hasMesh = function (mesh) {
  94865. return true;
  94866. };
  94867. /**
  94868. * Returns true if the layer contains information to display, otherwise false.
  94869. * @returns true if the glow layer should be rendered
  94870. */
  94871. EffectLayer.prototype.shouldRender = function () {
  94872. return this.isEnabled && this._shouldRender;
  94873. };
  94874. /**
  94875. * Returns true if the mesh should render, otherwise false.
  94876. * @param mesh The mesh to render
  94877. * @returns true if it should render otherwise false
  94878. */
  94879. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  94880. return true;
  94881. };
  94882. /**
  94883. * Returns true if the mesh should render, otherwise false.
  94884. * @param mesh The mesh to render
  94885. * @returns true if it should render otherwise false
  94886. */
  94887. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  94888. return true;
  94889. };
  94890. /**
  94891. * Renders the submesh passed in parameter to the generation map.
  94892. */
  94893. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  94894. var _this = this;
  94895. if (!this.shouldRender()) {
  94896. return;
  94897. }
  94898. var material = subMesh.getMaterial();
  94899. var mesh = subMesh.getRenderingMesh();
  94900. var scene = this._scene;
  94901. var engine = scene.getEngine();
  94902. if (!material) {
  94903. return;
  94904. }
  94905. // Do not block in blend mode.
  94906. if (material.needAlphaBlendingForMesh(mesh)) {
  94907. return;
  94908. }
  94909. // Culling
  94910. engine.setState(material.backFaceCulling);
  94911. // Managing instances
  94912. var batch = mesh._getInstancesRenderList(subMesh._id);
  94913. if (batch.mustReturn) {
  94914. return;
  94915. }
  94916. // Early Exit per mesh
  94917. if (!this._shouldRenderMesh(mesh)) {
  94918. return;
  94919. }
  94920. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  94921. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  94922. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  94923. engine.enableEffect(this._effectLayerMapGenerationEffect);
  94924. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  94925. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  94926. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  94927. // Alpha test
  94928. if (material && material.needAlphaTesting()) {
  94929. var alphaTexture = material.getAlphaTestTexture();
  94930. if (alphaTexture) {
  94931. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  94932. var textureMatrix = alphaTexture.getTextureMatrix();
  94933. if (textureMatrix) {
  94934. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  94935. }
  94936. }
  94937. }
  94938. // Glow emissive only
  94939. if (this._emissiveTextureAndColor.texture) {
  94940. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  94941. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  94942. }
  94943. // Bones
  94944. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  94945. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  94946. }
  94947. // Morph targets
  94948. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  94949. // Draw
  94950. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  94951. }
  94952. else {
  94953. // Need to reset refresh rate of the shadowMap
  94954. this._mainTexture.resetRefreshCounter();
  94955. }
  94956. };
  94957. /**
  94958. * Rebuild the required buffers.
  94959. * @hidden Internal use only.
  94960. */
  94961. EffectLayer.prototype._rebuild = function () {
  94962. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94963. if (vb) {
  94964. vb._rebuild();
  94965. }
  94966. this._generateIndexBuffer();
  94967. };
  94968. /**
  94969. * Dispose only the render target textures and post process.
  94970. */
  94971. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  94972. this._mainTexture.dispose();
  94973. for (var i = 0; i < this._postProcesses.length; i++) {
  94974. if (this._postProcesses[i]) {
  94975. this._postProcesses[i].dispose();
  94976. }
  94977. }
  94978. this._postProcesses = [];
  94979. for (var i = 0; i < this._textures.length; i++) {
  94980. if (this._textures[i]) {
  94981. this._textures[i].dispose();
  94982. }
  94983. }
  94984. this._textures = [];
  94985. };
  94986. /**
  94987. * Dispose the highlight layer and free resources.
  94988. */
  94989. EffectLayer.prototype.dispose = function () {
  94990. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94991. if (vertexBuffer) {
  94992. vertexBuffer.dispose();
  94993. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  94994. }
  94995. if (this._indexBuffer) {
  94996. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  94997. this._indexBuffer = null;
  94998. }
  94999. // Clean textures and post processes
  95000. this._disposeTextureAndPostProcesses();
  95001. // Remove from scene
  95002. var index = this._scene.effectLayers.indexOf(this, 0);
  95003. if (index > -1) {
  95004. this._scene.effectLayers.splice(index, 1);
  95005. }
  95006. // Callback
  95007. this.onDisposeObservable.notifyObservers(this);
  95008. this.onDisposeObservable.clear();
  95009. this.onBeforeRenderMainTextureObservable.clear();
  95010. this.onBeforeComposeObservable.clear();
  95011. this.onAfterComposeObservable.clear();
  95012. this.onSizeChangedObservable.clear();
  95013. };
  95014. /**
  95015. * Gets the class name of the effect layer
  95016. * @returns the string with the class name of the effect layer
  95017. */
  95018. EffectLayer.prototype.getClassName = function () {
  95019. return "EffectLayer";
  95020. };
  95021. /**
  95022. * Creates an effect layer from parsed effect layer data
  95023. * @param parsedEffectLayer defines effect layer data
  95024. * @param scene defines the current scene
  95025. * @param rootUrl defines the root URL containing the effect layer information
  95026. * @returns a parsed effect Layer
  95027. */
  95028. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  95029. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  95030. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  95031. };
  95032. __decorate([
  95033. BABYLON.serialize()
  95034. ], EffectLayer.prototype, "name", void 0);
  95035. __decorate([
  95036. BABYLON.serializeAsColor4()
  95037. ], EffectLayer.prototype, "neutralColor", void 0);
  95038. __decorate([
  95039. BABYLON.serialize()
  95040. ], EffectLayer.prototype, "isEnabled", void 0);
  95041. __decorate([
  95042. BABYLON.serializeAsCameraReference()
  95043. ], EffectLayer.prototype, "camera", null);
  95044. return EffectLayer;
  95045. }());
  95046. BABYLON.EffectLayer = EffectLayer;
  95047. })(BABYLON || (BABYLON = {}));
  95048. //# sourceMappingURL=babylon.effectLayer.js.map
  95049. var BABYLON;
  95050. (function (BABYLON) {
  95051. /**
  95052. * Special Glow Blur post process only blurring the alpha channel
  95053. * It enforces keeping the most luminous color in the color channel.
  95054. */
  95055. var GlowBlurPostProcess = /** @class */ (function (_super) {
  95056. __extends(GlowBlurPostProcess, _super);
  95057. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  95058. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  95059. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  95060. _this.direction = direction;
  95061. _this.kernel = kernel;
  95062. _this.onApplyObservable.add(function (effect) {
  95063. effect.setFloat2("screenSize", _this.width, _this.height);
  95064. effect.setVector2("direction", _this.direction);
  95065. effect.setFloat("blurWidth", _this.kernel);
  95066. });
  95067. return _this;
  95068. }
  95069. return GlowBlurPostProcess;
  95070. }(BABYLON.PostProcess));
  95071. /**
  95072. * The highlight layer Helps adding a glow effect around a mesh.
  95073. *
  95074. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  95075. * glowy meshes to your scene.
  95076. *
  95077. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  95078. */
  95079. var HighlightLayer = /** @class */ (function (_super) {
  95080. __extends(HighlightLayer, _super);
  95081. /**
  95082. * Instantiates a new highlight Layer and references it to the scene..
  95083. * @param name The name of the layer
  95084. * @param scene The scene to use the layer in
  95085. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  95086. */
  95087. function HighlightLayer(name, scene, options) {
  95088. var _this = _super.call(this, name, scene) || this;
  95089. _this.name = name;
  95090. /**
  95091. * Specifies whether or not the inner glow is ACTIVE in the layer.
  95092. */
  95093. _this.innerGlow = true;
  95094. /**
  95095. * Specifies whether or not the outer glow is ACTIVE in the layer.
  95096. */
  95097. _this.outerGlow = true;
  95098. /**
  95099. * An event triggered when the highlight layer is being blurred.
  95100. */
  95101. _this.onBeforeBlurObservable = new BABYLON.Observable();
  95102. /**
  95103. * An event triggered when the highlight layer has been blurred.
  95104. */
  95105. _this.onAfterBlurObservable = new BABYLON.Observable();
  95106. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  95107. _this._meshes = {};
  95108. _this._excludedMeshes = {};
  95109. _this.neutralColor = HighlightLayer.NeutralColor;
  95110. // Warn on stencil
  95111. if (!_this._engine.isStencilEnable) {
  95112. 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 }");
  95113. }
  95114. // Adapt options
  95115. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  95116. // Initialize the layer
  95117. _this._init({
  95118. alphaBlendingMode: _this._options.alphaBlendingMode,
  95119. camera: _this._options.camera,
  95120. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  95121. mainTextureRatio: _this._options.mainTextureRatio
  95122. });
  95123. // Do not render as long as no meshes have been added
  95124. _this._shouldRender = false;
  95125. return _this;
  95126. }
  95127. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  95128. /**
  95129. * Gets the horizontal size of the blur.
  95130. */
  95131. get: function () {
  95132. return this._horizontalBlurPostprocess.kernel;
  95133. },
  95134. /**
  95135. * Specifies the horizontal size of the blur.
  95136. */
  95137. set: function (value) {
  95138. this._horizontalBlurPostprocess.kernel = value;
  95139. },
  95140. enumerable: true,
  95141. configurable: true
  95142. });
  95143. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  95144. /**
  95145. * Gets the vertical size of the blur.
  95146. */
  95147. get: function () {
  95148. return this._verticalBlurPostprocess.kernel;
  95149. },
  95150. /**
  95151. * Specifies the vertical size of the blur.
  95152. */
  95153. set: function (value) {
  95154. this._verticalBlurPostprocess.kernel = value;
  95155. },
  95156. enumerable: true,
  95157. configurable: true
  95158. });
  95159. /**
  95160. * Get the effect name of the layer.
  95161. * @return The effect name
  95162. */
  95163. HighlightLayer.prototype.getEffectName = function () {
  95164. return HighlightLayer.EffectName;
  95165. };
  95166. /**
  95167. * Create the merge effect. This is the shader use to blit the information back
  95168. * to the main canvas at the end of the scene rendering.
  95169. */
  95170. HighlightLayer.prototype._createMergeEffect = function () {
  95171. // Effect
  95172. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  95173. };
  95174. /**
  95175. * Creates the render target textures and post processes used in the highlight layer.
  95176. */
  95177. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  95178. var _this = this;
  95179. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  95180. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  95181. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  95182. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  95183. var textureType = 0;
  95184. if (this._engine.getCaps().textureHalfFloatRender) {
  95185. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95186. }
  95187. else {
  95188. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95189. }
  95190. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  95191. width: blurTextureWidth,
  95192. height: blurTextureHeight
  95193. }, this._scene, false, true, textureType);
  95194. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95195. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95196. this._blurTexture.anisotropicFilteringLevel = 16;
  95197. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  95198. this._blurTexture.renderParticles = false;
  95199. this._blurTexture.ignoreCameraViewport = true;
  95200. this._textures = [this._blurTexture];
  95201. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  95202. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  95203. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  95204. effect.setTexture("textureSampler", _this._mainTexture);
  95205. });
  95206. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  95207. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  95208. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  95209. });
  95210. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  95211. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  95212. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  95213. });
  95214. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  95215. }
  95216. else {
  95217. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  95218. width: blurTextureWidth,
  95219. height: blurTextureHeight
  95220. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95221. this._horizontalBlurPostprocess.width = blurTextureWidth;
  95222. this._horizontalBlurPostprocess.height = blurTextureHeight;
  95223. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  95224. effect.setTexture("textureSampler", _this._mainTexture);
  95225. });
  95226. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  95227. width: blurTextureWidth,
  95228. height: blurTextureHeight
  95229. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95230. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  95231. }
  95232. this._mainTexture.onAfterUnbindObservable.add(function () {
  95233. _this.onBeforeBlurObservable.notifyObservers(_this);
  95234. var internalTexture = _this._blurTexture.getInternalTexture();
  95235. if (internalTexture) {
  95236. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  95237. }
  95238. _this.onAfterBlurObservable.notifyObservers(_this);
  95239. });
  95240. // Prevent autoClear.
  95241. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  95242. };
  95243. /**
  95244. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  95245. */
  95246. HighlightLayer.prototype.needStencil = function () {
  95247. return true;
  95248. };
  95249. /**
  95250. * Checks for the readiness of the element composing the layer.
  95251. * @param subMesh the mesh to check for
  95252. * @param useInstances specify wether or not to use instances to render the mesh
  95253. * @param emissiveTexture the associated emissive texture used to generate the glow
  95254. * @return true if ready otherwise, false
  95255. */
  95256. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  95257. var material = subMesh.getMaterial();
  95258. var mesh = subMesh.getRenderingMesh();
  95259. if (!material || !mesh || !this._meshes) {
  95260. return false;
  95261. }
  95262. var emissiveTexture = null;
  95263. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  95264. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  95265. emissiveTexture = material.emissiveTexture;
  95266. }
  95267. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  95268. };
  95269. /**
  95270. * Implementation specific of rendering the generating effect on the main canvas.
  95271. * @param effect The effect used to render through
  95272. */
  95273. HighlightLayer.prototype._internalRender = function (effect) {
  95274. // Texture
  95275. effect.setTexture("textureSampler", this._blurTexture);
  95276. // Cache
  95277. var engine = this._engine;
  95278. var previousStencilBuffer = engine.getStencilBuffer();
  95279. var previousStencilFunction = engine.getStencilFunction();
  95280. var previousStencilMask = engine.getStencilMask();
  95281. var previousStencilOperationPass = engine.getStencilOperationPass();
  95282. var previousStencilOperationFail = engine.getStencilOperationFail();
  95283. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  95284. var previousStencilReference = engine.getStencilFunctionReference();
  95285. // Stencil operations
  95286. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  95287. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  95288. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  95289. // Draw order
  95290. engine.setStencilMask(0x00);
  95291. engine.setStencilBuffer(true);
  95292. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  95293. // 2 passes inner outer
  95294. if (this.outerGlow) {
  95295. effect.setFloat("offset", 0);
  95296. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  95297. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  95298. }
  95299. if (this.innerGlow) {
  95300. effect.setFloat("offset", 1);
  95301. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  95302. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  95303. }
  95304. // Restore Cache
  95305. engine.setStencilFunction(previousStencilFunction);
  95306. engine.setStencilMask(previousStencilMask);
  95307. engine.setStencilBuffer(previousStencilBuffer);
  95308. engine.setStencilOperationPass(previousStencilOperationPass);
  95309. engine.setStencilOperationFail(previousStencilOperationFail);
  95310. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  95311. engine.setStencilFunctionReference(previousStencilReference);
  95312. };
  95313. /**
  95314. * Returns true if the layer contains information to display, otherwise false.
  95315. */
  95316. HighlightLayer.prototype.shouldRender = function () {
  95317. if (_super.prototype.shouldRender.call(this)) {
  95318. return this._meshes ? true : false;
  95319. }
  95320. return false;
  95321. };
  95322. /**
  95323. * Returns true if the mesh should render, otherwise false.
  95324. * @param mesh The mesh to render
  95325. * @returns true if it should render otherwise false
  95326. */
  95327. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  95328. // Excluded Mesh
  95329. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  95330. return false;
  95331. }
  95332. ;
  95333. return true;
  95334. };
  95335. /**
  95336. * Sets the required values for both the emissive texture and and the main color.
  95337. */
  95338. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  95339. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  95340. if (highlightLayerMesh) {
  95341. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  95342. }
  95343. else {
  95344. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  95345. }
  95346. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  95347. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  95348. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  95349. }
  95350. else {
  95351. this._emissiveTextureAndColor.texture = null;
  95352. }
  95353. };
  95354. /**
  95355. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  95356. * @param mesh The mesh to exclude from the highlight layer
  95357. */
  95358. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  95359. if (!this._excludedMeshes) {
  95360. return;
  95361. }
  95362. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  95363. if (!meshExcluded) {
  95364. this._excludedMeshes[mesh.uniqueId] = {
  95365. mesh: mesh,
  95366. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  95367. mesh.getEngine().setStencilBuffer(false);
  95368. }),
  95369. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  95370. mesh.getEngine().setStencilBuffer(true);
  95371. }),
  95372. };
  95373. }
  95374. };
  95375. /**
  95376. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  95377. * @param mesh The mesh to highlight
  95378. */
  95379. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  95380. if (!this._excludedMeshes) {
  95381. return;
  95382. }
  95383. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  95384. if (meshExcluded) {
  95385. if (meshExcluded.beforeRender) {
  95386. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  95387. }
  95388. if (meshExcluded.afterRender) {
  95389. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  95390. }
  95391. }
  95392. this._excludedMeshes[mesh.uniqueId] = null;
  95393. };
  95394. /**
  95395. * Determine if a given mesh will be highlighted by the current HighlightLayer
  95396. * @param mesh mesh to test
  95397. * @returns true if the mesh will be highlighted by the current HighlightLayer
  95398. */
  95399. HighlightLayer.prototype.hasMesh = function (mesh) {
  95400. if (!this._meshes) {
  95401. return false;
  95402. }
  95403. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  95404. };
  95405. /**
  95406. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  95407. * @param mesh The mesh to highlight
  95408. * @param color The color of the highlight
  95409. * @param glowEmissiveOnly Extract the glow from the emissive texture
  95410. */
  95411. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  95412. var _this = this;
  95413. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  95414. if (!this._meshes) {
  95415. return;
  95416. }
  95417. var meshHighlight = this._meshes[mesh.uniqueId];
  95418. if (meshHighlight) {
  95419. meshHighlight.color = color;
  95420. }
  95421. else {
  95422. this._meshes[mesh.uniqueId] = {
  95423. mesh: mesh,
  95424. color: color,
  95425. // Lambda required for capture due to Observable this context
  95426. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  95427. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  95428. _this._defaultStencilReference(mesh);
  95429. }
  95430. else {
  95431. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  95432. }
  95433. }),
  95434. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  95435. glowEmissiveOnly: glowEmissiveOnly
  95436. };
  95437. }
  95438. this._shouldRender = true;
  95439. };
  95440. /**
  95441. * Remove a mesh from the highlight layer in order to make it stop glowing.
  95442. * @param mesh The mesh to highlight
  95443. */
  95444. HighlightLayer.prototype.removeMesh = function (mesh) {
  95445. if (!this._meshes) {
  95446. return;
  95447. }
  95448. var meshHighlight = this._meshes[mesh.uniqueId];
  95449. if (meshHighlight) {
  95450. if (meshHighlight.observerHighlight) {
  95451. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  95452. }
  95453. if (meshHighlight.observerDefault) {
  95454. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  95455. }
  95456. delete this._meshes[mesh.uniqueId];
  95457. }
  95458. this._shouldRender = false;
  95459. for (var meshHighlightToCheck in this._meshes) {
  95460. if (this._meshes[meshHighlightToCheck]) {
  95461. this._shouldRender = true;
  95462. break;
  95463. }
  95464. }
  95465. };
  95466. /**
  95467. * Force the stencil to the normal expected value for none glowing parts
  95468. */
  95469. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  95470. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  95471. };
  95472. /**
  95473. * Free any resources and references associated to a mesh.
  95474. * Internal use
  95475. * @param mesh The mesh to free.
  95476. */
  95477. HighlightLayer.prototype._disposeMesh = function (mesh) {
  95478. this.removeMesh(mesh);
  95479. this.removeExcludedMesh(mesh);
  95480. };
  95481. /**
  95482. * Dispose the highlight layer and free resources.
  95483. */
  95484. HighlightLayer.prototype.dispose = function () {
  95485. if (this._meshes) {
  95486. // Clean mesh references
  95487. for (var id in this._meshes) {
  95488. var meshHighlight = this._meshes[id];
  95489. if (meshHighlight && meshHighlight.mesh) {
  95490. if (meshHighlight.observerHighlight) {
  95491. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  95492. }
  95493. if (meshHighlight.observerDefault) {
  95494. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  95495. }
  95496. }
  95497. }
  95498. this._meshes = null;
  95499. }
  95500. if (this._excludedMeshes) {
  95501. for (var id in this._excludedMeshes) {
  95502. var meshHighlight = this._excludedMeshes[id];
  95503. if (meshHighlight) {
  95504. if (meshHighlight.beforeRender) {
  95505. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  95506. }
  95507. if (meshHighlight.afterRender) {
  95508. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  95509. }
  95510. }
  95511. }
  95512. this._excludedMeshes = null;
  95513. }
  95514. _super.prototype.dispose.call(this);
  95515. };
  95516. /**
  95517. * Gets the class name of the effect layer
  95518. * @returns the string with the class name of the effect layer
  95519. */
  95520. HighlightLayer.prototype.getClassName = function () {
  95521. return "HighlightLayer";
  95522. };
  95523. /**
  95524. * Serializes this Highlight layer
  95525. * @returns a serialized Highlight layer object
  95526. */
  95527. HighlightLayer.prototype.serialize = function () {
  95528. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  95529. serializationObject.customType = "BABYLON.HighlightLayer";
  95530. // Highlighted meshes
  95531. serializationObject.meshes = [];
  95532. if (this._meshes) {
  95533. for (var m in this._meshes) {
  95534. var mesh = this._meshes[m];
  95535. if (mesh) {
  95536. serializationObject.meshes.push({
  95537. glowEmissiveOnly: mesh.glowEmissiveOnly,
  95538. color: mesh.color.asArray(),
  95539. meshId: mesh.mesh.id
  95540. });
  95541. }
  95542. }
  95543. }
  95544. // Excluded meshes
  95545. serializationObject.excludedMeshes = [];
  95546. if (this._excludedMeshes) {
  95547. for (var e in this._excludedMeshes) {
  95548. var excludedMesh = this._excludedMeshes[e];
  95549. if (excludedMesh) {
  95550. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  95551. }
  95552. }
  95553. }
  95554. return serializationObject;
  95555. };
  95556. /**
  95557. * Creates a Highlight layer from parsed Highlight layer data
  95558. * @param parsedHightlightLayer defines the Highlight layer data
  95559. * @param scene defines the current scene
  95560. * @param rootUrl defines the root URL containing the Highlight layer information
  95561. * @returns a parsed Highlight layer
  95562. */
  95563. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  95564. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  95565. var index;
  95566. // Excluded meshes
  95567. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  95568. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  95569. if (mesh) {
  95570. hl.addExcludedMesh(mesh);
  95571. }
  95572. }
  95573. // Included meshes
  95574. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  95575. var highlightedMesh = parsedHightlightLayer.meshes[index];
  95576. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  95577. if (mesh) {
  95578. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  95579. }
  95580. }
  95581. return hl;
  95582. };
  95583. /**
  95584. * Effect Name of the highlight layer.
  95585. */
  95586. HighlightLayer.EffectName = "HighlightLayer";
  95587. /**
  95588. * The neutral color used during the preparation of the glow effect.
  95589. * This is black by default as the blend operation is a blend operation.
  95590. */
  95591. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  95592. /**
  95593. * Stencil value used for glowing meshes.
  95594. */
  95595. HighlightLayer.GlowingMeshStencilReference = 0x02;
  95596. /**
  95597. * Stencil value used for the other meshes in the scene.
  95598. */
  95599. HighlightLayer.NormalMeshStencilReference = 0x01;
  95600. __decorate([
  95601. BABYLON.serialize()
  95602. ], HighlightLayer.prototype, "innerGlow", void 0);
  95603. __decorate([
  95604. BABYLON.serialize()
  95605. ], HighlightLayer.prototype, "outerGlow", void 0);
  95606. __decorate([
  95607. BABYLON.serialize()
  95608. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  95609. __decorate([
  95610. BABYLON.serialize()
  95611. ], HighlightLayer.prototype, "blurVerticalSize", null);
  95612. __decorate([
  95613. BABYLON.serialize("options")
  95614. ], HighlightLayer.prototype, "_options", void 0);
  95615. return HighlightLayer;
  95616. }(BABYLON.EffectLayer));
  95617. BABYLON.HighlightLayer = HighlightLayer;
  95618. })(BABYLON || (BABYLON = {}));
  95619. //# sourceMappingURL=babylon.highlightLayer.js.map
  95620. var BABYLON;
  95621. (function (BABYLON) {
  95622. /**
  95623. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  95624. *
  95625. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  95626. * glowy meshes to your scene.
  95627. *
  95628. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  95629. */
  95630. var GlowLayer = /** @class */ (function (_super) {
  95631. __extends(GlowLayer, _super);
  95632. /**
  95633. * Instantiates a new glow Layer and references it to the scene.
  95634. * @param name The name of the layer
  95635. * @param scene The scene to use the layer in
  95636. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  95637. */
  95638. function GlowLayer(name, scene, options) {
  95639. var _this = _super.call(this, name, scene) || this;
  95640. _this._intensity = 1.0;
  95641. _this._includedOnlyMeshes = [];
  95642. _this._excludedMeshes = [];
  95643. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  95644. // Adapt options
  95645. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  95646. // Initialize the layer
  95647. _this._init({
  95648. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  95649. camera: _this._options.camera,
  95650. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  95651. mainTextureRatio: _this._options.mainTextureRatio
  95652. });
  95653. return _this;
  95654. }
  95655. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  95656. /**
  95657. * Gets the kernel size of the blur.
  95658. */
  95659. get: function () {
  95660. return this._horizontalBlurPostprocess1.kernel;
  95661. },
  95662. /**
  95663. * Sets the kernel size of the blur.
  95664. */
  95665. set: function (value) {
  95666. this._horizontalBlurPostprocess1.kernel = value;
  95667. this._verticalBlurPostprocess1.kernel = value;
  95668. this._horizontalBlurPostprocess2.kernel = value;
  95669. this._verticalBlurPostprocess2.kernel = value;
  95670. },
  95671. enumerable: true,
  95672. configurable: true
  95673. });
  95674. Object.defineProperty(GlowLayer.prototype, "intensity", {
  95675. /**
  95676. * Gets the glow intensity.
  95677. */
  95678. get: function () {
  95679. return this._intensity;
  95680. },
  95681. /**
  95682. * Sets the glow intensity.
  95683. */
  95684. set: function (value) {
  95685. this._intensity = value;
  95686. },
  95687. enumerable: true,
  95688. configurable: true
  95689. });
  95690. /**
  95691. * Get the effect name of the layer.
  95692. * @return The effect name
  95693. */
  95694. GlowLayer.prototype.getEffectName = function () {
  95695. return GlowLayer.EffectName;
  95696. };
  95697. /**
  95698. * Create the merge effect. This is the shader use to blit the information back
  95699. * to the main canvas at the end of the scene rendering.
  95700. */
  95701. GlowLayer.prototype._createMergeEffect = function () {
  95702. // Effect
  95703. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  95704. };
  95705. /**
  95706. * Creates the render target textures and post processes used in the glow layer.
  95707. */
  95708. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  95709. var _this = this;
  95710. var blurTextureWidth = this._mainTextureDesiredSize.width;
  95711. var blurTextureHeight = this._mainTextureDesiredSize.height;
  95712. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  95713. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  95714. var textureType = 0;
  95715. if (this._engine.getCaps().textureHalfFloatRender) {
  95716. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95717. }
  95718. else {
  95719. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95720. }
  95721. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  95722. width: blurTextureWidth,
  95723. height: blurTextureHeight
  95724. }, this._scene, false, true, textureType);
  95725. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95726. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95727. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  95728. this._blurTexture1.renderParticles = false;
  95729. this._blurTexture1.ignoreCameraViewport = true;
  95730. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  95731. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  95732. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  95733. width: blurTextureWidth2,
  95734. height: blurTextureHeight2
  95735. }, this._scene, false, true, textureType);
  95736. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95737. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95738. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  95739. this._blurTexture2.renderParticles = false;
  95740. this._blurTexture2.ignoreCameraViewport = true;
  95741. this._textures = [this._blurTexture1, this._blurTexture2];
  95742. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  95743. width: blurTextureWidth,
  95744. height: blurTextureHeight
  95745. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95746. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  95747. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  95748. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  95749. effect.setTexture("textureSampler", _this._mainTexture);
  95750. });
  95751. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  95752. width: blurTextureWidth,
  95753. height: blurTextureHeight
  95754. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95755. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  95756. width: blurTextureWidth2,
  95757. height: blurTextureHeight2
  95758. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95759. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  95760. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  95761. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  95762. effect.setTexture("textureSampler", _this._blurTexture1);
  95763. });
  95764. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  95765. width: blurTextureWidth2,
  95766. height: blurTextureHeight2
  95767. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95768. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  95769. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  95770. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  95771. this._mainTexture.samples = this._options.mainTextureSamples;
  95772. this._mainTexture.onAfterUnbindObservable.add(function () {
  95773. var internalTexture = _this._blurTexture1.getInternalTexture();
  95774. if (internalTexture) {
  95775. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  95776. internalTexture = _this._blurTexture2.getInternalTexture();
  95777. if (internalTexture) {
  95778. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  95779. }
  95780. }
  95781. });
  95782. // Prevent autoClear.
  95783. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  95784. };
  95785. /**
  95786. * Checks for the readiness of the element composing the layer.
  95787. * @param subMesh the mesh to check for
  95788. * @param useInstances specify wether or not to use instances to render the mesh
  95789. * @param emissiveTexture the associated emissive texture used to generate the glow
  95790. * @return true if ready otherwise, false
  95791. */
  95792. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  95793. var material = subMesh.getMaterial();
  95794. var mesh = subMesh.getRenderingMesh();
  95795. if (!material || !mesh) {
  95796. return false;
  95797. }
  95798. var emissiveTexture = material.emissiveTexture;
  95799. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  95800. };
  95801. /**
  95802. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  95803. */
  95804. GlowLayer.prototype.needStencil = function () {
  95805. return false;
  95806. };
  95807. /**
  95808. * Implementation specific of rendering the generating effect on the main canvas.
  95809. * @param effect The effect used to render through
  95810. */
  95811. GlowLayer.prototype._internalRender = function (effect) {
  95812. // Texture
  95813. effect.setTexture("textureSampler", this._blurTexture1);
  95814. effect.setTexture("textureSampler2", this._blurTexture2);
  95815. effect.setFloat("offset", this._intensity);
  95816. // Cache
  95817. var engine = this._engine;
  95818. var previousStencilBuffer = engine.getStencilBuffer();
  95819. // Draw order
  95820. engine.setStencilBuffer(false);
  95821. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  95822. // Draw order
  95823. engine.setStencilBuffer(previousStencilBuffer);
  95824. };
  95825. /**
  95826. * Sets the required values for both the emissive texture and and the main color.
  95827. */
  95828. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  95829. var textureLevel = 1.0;
  95830. if (this.customEmissiveTextureSelector) {
  95831. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  95832. }
  95833. else {
  95834. if (material) {
  95835. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  95836. if (this._emissiveTextureAndColor.texture) {
  95837. textureLevel = this._emissiveTextureAndColor.texture.level;
  95838. }
  95839. }
  95840. else {
  95841. this._emissiveTextureAndColor.texture = null;
  95842. }
  95843. }
  95844. if (this.customEmissiveColorSelector) {
  95845. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  95846. }
  95847. else {
  95848. if (material.emissiveColor) {
  95849. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  95850. }
  95851. else {
  95852. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  95853. }
  95854. }
  95855. };
  95856. /**
  95857. * Returns true if the mesh should render, otherwise false.
  95858. * @param mesh The mesh to render
  95859. * @returns true if it should render otherwise false
  95860. */
  95861. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  95862. return this.hasMesh(mesh);
  95863. };
  95864. /**
  95865. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  95866. * @param mesh The mesh to exclude from the glow layer
  95867. */
  95868. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  95869. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  95870. this._excludedMeshes.push(mesh.uniqueId);
  95871. }
  95872. };
  95873. /**
  95874. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  95875. * @param mesh The mesh to remove
  95876. */
  95877. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  95878. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  95879. if (index !== -1) {
  95880. this._excludedMeshes.splice(index, 1);
  95881. }
  95882. };
  95883. /**
  95884. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  95885. * @param mesh The mesh to include in the glow layer
  95886. */
  95887. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  95888. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  95889. this._includedOnlyMeshes.push(mesh.uniqueId);
  95890. }
  95891. };
  95892. /**
  95893. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  95894. * @param mesh The mesh to remove
  95895. */
  95896. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  95897. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  95898. if (index !== -1) {
  95899. this._includedOnlyMeshes.splice(index, 1);
  95900. }
  95901. };
  95902. /**
  95903. * Determine if a given mesh will be used in the glow layer
  95904. * @param mesh The mesh to test
  95905. * @returns true if the mesh will be highlighted by the current glow layer
  95906. */
  95907. GlowLayer.prototype.hasMesh = function (mesh) {
  95908. // Included Mesh
  95909. if (this._includedOnlyMeshes.length) {
  95910. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  95911. }
  95912. ;
  95913. // Excluded Mesh
  95914. if (this._excludedMeshes.length) {
  95915. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  95916. }
  95917. ;
  95918. return true;
  95919. };
  95920. /**
  95921. * Free any resources and references associated to a mesh.
  95922. * Internal use
  95923. * @param mesh The mesh to free.
  95924. */
  95925. GlowLayer.prototype._disposeMesh = function (mesh) {
  95926. this.removeIncludedOnlyMesh(mesh);
  95927. this.removeExcludedMesh(mesh);
  95928. };
  95929. /**
  95930. * Gets the class name of the effect layer
  95931. * @returns the string with the class name of the effect layer
  95932. */
  95933. GlowLayer.prototype.getClassName = function () {
  95934. return "GlowLayer";
  95935. };
  95936. /**
  95937. * Serializes this glow layer
  95938. * @returns a serialized glow layer object
  95939. */
  95940. GlowLayer.prototype.serialize = function () {
  95941. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  95942. serializationObject.customType = "BABYLON.GlowLayer";
  95943. var index;
  95944. // Included meshes
  95945. serializationObject.includedMeshes = [];
  95946. if (this._includedOnlyMeshes.length) {
  95947. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  95948. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  95949. if (mesh) {
  95950. serializationObject.includedMeshes.push(mesh.id);
  95951. }
  95952. }
  95953. }
  95954. // Excluded meshes
  95955. serializationObject.excludedMeshes = [];
  95956. if (this._excludedMeshes.length) {
  95957. for (index = 0; index < this._excludedMeshes.length; index++) {
  95958. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  95959. if (mesh) {
  95960. serializationObject.excludedMeshes.push(mesh.id);
  95961. }
  95962. }
  95963. }
  95964. return serializationObject;
  95965. };
  95966. /**
  95967. * Creates a Glow Layer from parsed glow layer data
  95968. * @param parsedGlowLayer defines glow layer data
  95969. * @param scene defines the current scene
  95970. * @param rootUrl defines the root URL containing the glow layer information
  95971. * @returns a parsed Glow Layer
  95972. */
  95973. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  95974. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  95975. var index;
  95976. // Excluded meshes
  95977. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  95978. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  95979. if (mesh) {
  95980. gl.addExcludedMesh(mesh);
  95981. }
  95982. }
  95983. // Included meshes
  95984. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  95985. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  95986. if (mesh) {
  95987. gl.addIncludedOnlyMesh(mesh);
  95988. }
  95989. }
  95990. return gl;
  95991. };
  95992. /**
  95993. * Effect Name of the layer.
  95994. */
  95995. GlowLayer.EffectName = "GlowLayer";
  95996. /**
  95997. * The default blur kernel size used for the glow.
  95998. */
  95999. GlowLayer.DefaultBlurKernelSize = 32;
  96000. /**
  96001. * The default texture size ratio used for the glow.
  96002. */
  96003. GlowLayer.DefaultTextureRatio = 0.5;
  96004. __decorate([
  96005. BABYLON.serialize()
  96006. ], GlowLayer.prototype, "blurKernelSize", null);
  96007. __decorate([
  96008. BABYLON.serialize()
  96009. ], GlowLayer.prototype, "intensity", null);
  96010. __decorate([
  96011. BABYLON.serialize("options")
  96012. ], GlowLayer.prototype, "_options", void 0);
  96013. return GlowLayer;
  96014. }(BABYLON.EffectLayer));
  96015. BABYLON.GlowLayer = GlowLayer;
  96016. })(BABYLON || (BABYLON = {}));
  96017. //# sourceMappingURL=babylon.glowLayer.js.map
  96018. var BABYLON;
  96019. (function (BABYLON) {
  96020. /**
  96021. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  96022. */
  96023. var AssetTaskState;
  96024. (function (AssetTaskState) {
  96025. /**
  96026. * Initialization
  96027. */
  96028. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  96029. /**
  96030. * Running
  96031. */
  96032. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  96033. /**
  96034. * Done
  96035. */
  96036. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  96037. /**
  96038. * Error
  96039. */
  96040. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  96041. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  96042. /**
  96043. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  96044. */
  96045. var AbstractAssetTask = /** @class */ (function () {
  96046. /**
  96047. * Creates a new {BABYLON.AssetsManager}
  96048. * @param name defines the name of the task
  96049. */
  96050. function AbstractAssetTask(
  96051. /**
  96052. * Task name
  96053. */ name) {
  96054. this.name = name;
  96055. this._isCompleted = false;
  96056. this._taskState = AssetTaskState.INIT;
  96057. }
  96058. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  96059. /**
  96060. * Get if the task is completed
  96061. */
  96062. get: function () {
  96063. return this._isCompleted;
  96064. },
  96065. enumerable: true,
  96066. configurable: true
  96067. });
  96068. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  96069. /**
  96070. * Gets the current state of the task
  96071. */
  96072. get: function () {
  96073. return this._taskState;
  96074. },
  96075. enumerable: true,
  96076. configurable: true
  96077. });
  96078. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  96079. /**
  96080. * Gets the current error object (if task is in error)
  96081. */
  96082. get: function () {
  96083. return this._errorObject;
  96084. },
  96085. enumerable: true,
  96086. configurable: true
  96087. });
  96088. /**
  96089. * Internal only
  96090. * @hidden
  96091. */
  96092. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  96093. if (this._errorObject) {
  96094. return;
  96095. }
  96096. this._errorObject = {
  96097. message: message,
  96098. exception: exception
  96099. };
  96100. };
  96101. /**
  96102. * Execute the current task
  96103. * @param scene defines the scene where you want your assets to be loaded
  96104. * @param onSuccess is a callback called when the task is successfully executed
  96105. * @param onError is a callback called if an error occurs
  96106. */
  96107. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  96108. var _this = this;
  96109. this._taskState = AssetTaskState.RUNNING;
  96110. this.runTask(scene, function () {
  96111. _this.onDoneCallback(onSuccess, onError);
  96112. }, function (msg, exception) {
  96113. _this.onErrorCallback(onError, msg, exception);
  96114. });
  96115. };
  96116. /**
  96117. * Execute the current task
  96118. * @param scene defines the scene where you want your assets to be loaded
  96119. * @param onSuccess is a callback called when the task is successfully executed
  96120. * @param onError is a callback called if an error occurs
  96121. */
  96122. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96123. throw new Error("runTask is not implemented");
  96124. };
  96125. /**
  96126. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  96127. * This can be used with failed tasks that have the reason for failure fixed.
  96128. */
  96129. AbstractAssetTask.prototype.reset = function () {
  96130. this._taskState = AssetTaskState.INIT;
  96131. };
  96132. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  96133. this._taskState = AssetTaskState.ERROR;
  96134. this._errorObject = {
  96135. message: message,
  96136. exception: exception
  96137. };
  96138. if (this.onError) {
  96139. this.onError(this, message, exception);
  96140. }
  96141. onError();
  96142. };
  96143. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  96144. try {
  96145. this._taskState = AssetTaskState.DONE;
  96146. this._isCompleted = true;
  96147. if (this.onSuccess) {
  96148. this.onSuccess(this);
  96149. }
  96150. onSuccess();
  96151. }
  96152. catch (e) {
  96153. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  96154. }
  96155. };
  96156. return AbstractAssetTask;
  96157. }());
  96158. BABYLON.AbstractAssetTask = AbstractAssetTask;
  96159. /**
  96160. * Class used to share progress information about assets loading
  96161. */
  96162. var AssetsProgressEvent = /** @class */ (function () {
  96163. /**
  96164. * Creates a {BABYLON.AssetsProgressEvent}
  96165. * @param remainingCount defines the number of remaining tasks to process
  96166. * @param totalCount defines the total number of tasks
  96167. * @param task defines the task that was just processed
  96168. */
  96169. function AssetsProgressEvent(remainingCount, totalCount, task) {
  96170. this.remainingCount = remainingCount;
  96171. this.totalCount = totalCount;
  96172. this.task = task;
  96173. }
  96174. return AssetsProgressEvent;
  96175. }());
  96176. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  96177. /**
  96178. * Define a task used by {BABYLON.AssetsManager} to load meshes
  96179. */
  96180. var MeshAssetTask = /** @class */ (function (_super) {
  96181. __extends(MeshAssetTask, _super);
  96182. /**
  96183. * Creates a new {BABYLON.MeshAssetTask}
  96184. * @param name defines the name of the task
  96185. * @param meshesNames defines the list of mesh's names you want to load
  96186. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  96187. * @param sceneFilename defines the filename of the scene to load from
  96188. */
  96189. function MeshAssetTask(
  96190. /**
  96191. * Defines the name of the task
  96192. */
  96193. name,
  96194. /**
  96195. * Defines the list of mesh's names you want to load
  96196. */
  96197. meshesNames,
  96198. /**
  96199. * Defines the root url to use as a base to load your meshes and associated resources
  96200. */
  96201. rootUrl,
  96202. /**
  96203. * Defines the filename of the scene to load from
  96204. */
  96205. sceneFilename) {
  96206. var _this = _super.call(this, name) || this;
  96207. _this.name = name;
  96208. _this.meshesNames = meshesNames;
  96209. _this.rootUrl = rootUrl;
  96210. _this.sceneFilename = sceneFilename;
  96211. return _this;
  96212. }
  96213. /**
  96214. * Execute the current task
  96215. * @param scene defines the scene where you want your assets to be loaded
  96216. * @param onSuccess is a callback called when the task is successfully executed
  96217. * @param onError is a callback called if an error occurs
  96218. */
  96219. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96220. var _this = this;
  96221. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  96222. _this.loadedMeshes = meshes;
  96223. _this.loadedParticleSystems = particleSystems;
  96224. _this.loadedSkeletons = skeletons;
  96225. onSuccess();
  96226. }, null, function (scene, message, exception) {
  96227. onError(message, exception);
  96228. });
  96229. };
  96230. return MeshAssetTask;
  96231. }(AbstractAssetTask));
  96232. BABYLON.MeshAssetTask = MeshAssetTask;
  96233. /**
  96234. * Define a task used by {BABYLON.AssetsManager} to load text content
  96235. */
  96236. var TextFileAssetTask = /** @class */ (function (_super) {
  96237. __extends(TextFileAssetTask, _super);
  96238. /**
  96239. * Creates a new TextFileAssetTask object
  96240. * @param name defines the name of the task
  96241. * @param url defines the location of the file to load
  96242. */
  96243. function TextFileAssetTask(
  96244. /**
  96245. * Defines the name of the task
  96246. */
  96247. name,
  96248. /**
  96249. * Defines the location of the file to load
  96250. */
  96251. url) {
  96252. var _this = _super.call(this, name) || this;
  96253. _this.name = name;
  96254. _this.url = url;
  96255. return _this;
  96256. }
  96257. /**
  96258. * Execute the current task
  96259. * @param scene defines the scene where you want your assets to be loaded
  96260. * @param onSuccess is a callback called when the task is successfully executed
  96261. * @param onError is a callback called if an error occurs
  96262. */
  96263. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96264. var _this = this;
  96265. scene._loadFile(this.url, function (data) {
  96266. _this.text = data;
  96267. onSuccess();
  96268. }, undefined, false, false, function (request, exception) {
  96269. if (request) {
  96270. onError(request.status + " " + request.statusText, exception);
  96271. }
  96272. });
  96273. };
  96274. return TextFileAssetTask;
  96275. }(AbstractAssetTask));
  96276. BABYLON.TextFileAssetTask = TextFileAssetTask;
  96277. /**
  96278. * Define a task used by {BABYLON.AssetsManager} to load binary data
  96279. */
  96280. var BinaryFileAssetTask = /** @class */ (function (_super) {
  96281. __extends(BinaryFileAssetTask, _super);
  96282. /**
  96283. * Creates a new BinaryFileAssetTask object
  96284. * @param name defines the name of the new task
  96285. * @param url defines the location of the file to load
  96286. */
  96287. function BinaryFileAssetTask(
  96288. /**
  96289. * Defines the name of the task
  96290. */
  96291. name,
  96292. /**
  96293. * Defines the location of the file to load
  96294. */
  96295. url) {
  96296. var _this = _super.call(this, name) || this;
  96297. _this.name = name;
  96298. _this.url = url;
  96299. return _this;
  96300. }
  96301. /**
  96302. * Execute the current task
  96303. * @param scene defines the scene where you want your assets to be loaded
  96304. * @param onSuccess is a callback called when the task is successfully executed
  96305. * @param onError is a callback called if an error occurs
  96306. */
  96307. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96308. var _this = this;
  96309. scene._loadFile(this.url, function (data) {
  96310. _this.data = data;
  96311. onSuccess();
  96312. }, undefined, true, true, function (request, exception) {
  96313. if (request) {
  96314. onError(request.status + " " + request.statusText, exception);
  96315. }
  96316. });
  96317. };
  96318. return BinaryFileAssetTask;
  96319. }(AbstractAssetTask));
  96320. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  96321. /**
  96322. * Define a task used by {BABYLON.AssetsManager} to load images
  96323. */
  96324. var ImageAssetTask = /** @class */ (function (_super) {
  96325. __extends(ImageAssetTask, _super);
  96326. /**
  96327. * Creates a new ImageAssetTask
  96328. * @param name defines the name of the task
  96329. * @param url defines the location of the image to load
  96330. */
  96331. function ImageAssetTask(
  96332. /**
  96333. * Defines the name of the task
  96334. */
  96335. name,
  96336. /**
  96337. * Defines the location of the image to load
  96338. */
  96339. url) {
  96340. var _this = _super.call(this, name) || this;
  96341. _this.name = name;
  96342. _this.url = url;
  96343. return _this;
  96344. }
  96345. /**
  96346. * Execute the current task
  96347. * @param scene defines the scene where you want your assets to be loaded
  96348. * @param onSuccess is a callback called when the task is successfully executed
  96349. * @param onError is a callback called if an error occurs
  96350. */
  96351. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96352. var _this = this;
  96353. var img = new Image();
  96354. BABYLON.Tools.SetCorsBehavior(this.url, img);
  96355. img.onload = function () {
  96356. _this.image = img;
  96357. onSuccess();
  96358. };
  96359. img.onerror = function (err) {
  96360. onError("Error loading image", err);
  96361. };
  96362. img.src = this.url;
  96363. };
  96364. return ImageAssetTask;
  96365. }(AbstractAssetTask));
  96366. BABYLON.ImageAssetTask = ImageAssetTask;
  96367. /**
  96368. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  96369. */
  96370. var TextureAssetTask = /** @class */ (function (_super) {
  96371. __extends(TextureAssetTask, _super);
  96372. /**
  96373. * Creates a new TextureAssetTask object
  96374. * @param name defines the name of the task
  96375. * @param url defines the location of the file to load
  96376. * @param noMipmap defines if mipmap should not be generated (default is false)
  96377. * @param invertY defines if texture must be inverted on Y axis (default is false)
  96378. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  96379. */
  96380. function TextureAssetTask(
  96381. /**
  96382. * Defines the name of the task
  96383. */
  96384. name,
  96385. /**
  96386. * Defines the location of the file to load
  96387. */
  96388. url,
  96389. /**
  96390. * Defines if mipmap should not be generated (default is false)
  96391. */
  96392. noMipmap,
  96393. /**
  96394. * Defines if texture must be inverted on Y axis (default is false)
  96395. */
  96396. invertY,
  96397. /**
  96398. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  96399. */
  96400. samplingMode) {
  96401. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  96402. var _this = _super.call(this, name) || this;
  96403. _this.name = name;
  96404. _this.url = url;
  96405. _this.noMipmap = noMipmap;
  96406. _this.invertY = invertY;
  96407. _this.samplingMode = samplingMode;
  96408. return _this;
  96409. }
  96410. /**
  96411. * Execute the current task
  96412. * @param scene defines the scene where you want your assets to be loaded
  96413. * @param onSuccess is a callback called when the task is successfully executed
  96414. * @param onError is a callback called if an error occurs
  96415. */
  96416. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96417. var onload = function () {
  96418. onSuccess();
  96419. };
  96420. var onerror = function (message, exception) {
  96421. onError(message, exception);
  96422. };
  96423. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  96424. };
  96425. return TextureAssetTask;
  96426. }(AbstractAssetTask));
  96427. BABYLON.TextureAssetTask = TextureAssetTask;
  96428. /**
  96429. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  96430. */
  96431. var CubeTextureAssetTask = /** @class */ (function (_super) {
  96432. __extends(CubeTextureAssetTask, _super);
  96433. /**
  96434. * Creates a new CubeTextureAssetTask
  96435. * @param name defines the name of the task
  96436. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  96437. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  96438. * @param noMipmap defines if mipmaps should not be generated (default is false)
  96439. * @param files defines the explicit list of files (undefined by default)
  96440. */
  96441. function CubeTextureAssetTask(
  96442. /**
  96443. * Defines the name of the task
  96444. */
  96445. name,
  96446. /**
  96447. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  96448. */
  96449. url,
  96450. /**
  96451. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  96452. */
  96453. extensions,
  96454. /**
  96455. * Defines if mipmaps should not be generated (default is false)
  96456. */
  96457. noMipmap,
  96458. /**
  96459. * Defines the explicit list of files (undefined by default)
  96460. */
  96461. files) {
  96462. var _this = _super.call(this, name) || this;
  96463. _this.name = name;
  96464. _this.url = url;
  96465. _this.extensions = extensions;
  96466. _this.noMipmap = noMipmap;
  96467. _this.files = files;
  96468. return _this;
  96469. }
  96470. /**
  96471. * Execute the current task
  96472. * @param scene defines the scene where you want your assets to be loaded
  96473. * @param onSuccess is a callback called when the task is successfully executed
  96474. * @param onError is a callback called if an error occurs
  96475. */
  96476. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96477. var onload = function () {
  96478. onSuccess();
  96479. };
  96480. var onerror = function (message, exception) {
  96481. onError(message, exception);
  96482. };
  96483. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  96484. };
  96485. return CubeTextureAssetTask;
  96486. }(AbstractAssetTask));
  96487. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  96488. /**
  96489. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  96490. */
  96491. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  96492. __extends(HDRCubeTextureAssetTask, _super);
  96493. /**
  96494. * Creates a new HDRCubeTextureAssetTask object
  96495. * @param name defines the name of the task
  96496. * @param url defines the location of the file to load
  96497. * @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.
  96498. * @param noMipmap defines if mipmaps should not be generated (default is false)
  96499. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  96500. * @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)
  96501. * @param reserved Internal use only
  96502. */
  96503. function HDRCubeTextureAssetTask(
  96504. /**
  96505. * Defines the name of the task
  96506. */
  96507. name,
  96508. /**
  96509. * Defines the location of the file to load
  96510. */
  96511. url,
  96512. /**
  96513. * Defines the desired size (the more it increases the longer the generation will be)
  96514. */
  96515. size,
  96516. /**
  96517. * Defines if mipmaps should not be generated (default is false)
  96518. */
  96519. noMipmap,
  96520. /**
  96521. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  96522. */
  96523. generateHarmonics,
  96524. /**
  96525. * 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)
  96526. */
  96527. gammaSpace,
  96528. /**
  96529. * Internal Use Only
  96530. */
  96531. reserved) {
  96532. if (noMipmap === void 0) { noMipmap = false; }
  96533. if (generateHarmonics === void 0) { generateHarmonics = true; }
  96534. if (gammaSpace === void 0) { gammaSpace = false; }
  96535. if (reserved === void 0) { reserved = false; }
  96536. var _this = _super.call(this, name) || this;
  96537. _this.name = name;
  96538. _this.url = url;
  96539. _this.size = size;
  96540. _this.noMipmap = noMipmap;
  96541. _this.generateHarmonics = generateHarmonics;
  96542. _this.gammaSpace = gammaSpace;
  96543. _this.reserved = reserved;
  96544. return _this;
  96545. }
  96546. /**
  96547. * Execute the current task
  96548. * @param scene defines the scene where you want your assets to be loaded
  96549. * @param onSuccess is a callback called when the task is successfully executed
  96550. * @param onError is a callback called if an error occurs
  96551. */
  96552. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  96553. var onload = function () {
  96554. onSuccess();
  96555. };
  96556. var onerror = function (message, exception) {
  96557. onError(message, exception);
  96558. };
  96559. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  96560. };
  96561. return HDRCubeTextureAssetTask;
  96562. }(AbstractAssetTask));
  96563. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  96564. /**
  96565. * This class can be used to easily import assets into a scene
  96566. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  96567. */
  96568. var AssetsManager = /** @class */ (function () {
  96569. /**
  96570. * Creates a new AssetsManager
  96571. * @param scene defines the scene to work on
  96572. */
  96573. function AssetsManager(scene) {
  96574. this._isLoading = false;
  96575. this._tasks = new Array();
  96576. this._waitingTasksCount = 0;
  96577. this._totalTasksCount = 0;
  96578. /**
  96579. * Observable called when all tasks are processed
  96580. */
  96581. this.onTaskSuccessObservable = new BABYLON.Observable();
  96582. /**
  96583. * Observable called when a task had an error
  96584. */
  96585. this.onTaskErrorObservable = new BABYLON.Observable();
  96586. /**
  96587. * Observable called when a task is successful
  96588. */
  96589. this.onTasksDoneObservable = new BABYLON.Observable();
  96590. /**
  96591. * Observable called when a task is done (whatever the result is)
  96592. */
  96593. this.onProgressObservable = new BABYLON.Observable();
  96594. /**
  96595. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  96596. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  96597. */
  96598. this.useDefaultLoadingScreen = true;
  96599. this._scene = scene;
  96600. }
  96601. /**
  96602. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  96603. * @param taskName defines the name of the new task
  96604. * @param meshesNames defines the name of meshes to load
  96605. * @param rootUrl defines the root url to use to locate files
  96606. * @param sceneFilename defines the filename of the scene file
  96607. * @returns a new {BABYLON.MeshAssetTask} object
  96608. */
  96609. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  96610. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  96611. this._tasks.push(task);
  96612. return task;
  96613. };
  96614. /**
  96615. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  96616. * @param taskName defines the name of the new task
  96617. * @param url defines the url of the file to load
  96618. * @returns a new {BABYLON.TextFileAssetTask} object
  96619. */
  96620. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  96621. var task = new TextFileAssetTask(taskName, url);
  96622. this._tasks.push(task);
  96623. return task;
  96624. };
  96625. /**
  96626. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  96627. * @param taskName defines the name of the new task
  96628. * @param url defines the url of the file to load
  96629. * @returns a new {BABYLON.BinaryFileAssetTask} object
  96630. */
  96631. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  96632. var task = new BinaryFileAssetTask(taskName, url);
  96633. this._tasks.push(task);
  96634. return task;
  96635. };
  96636. /**
  96637. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  96638. * @param taskName defines the name of the new task
  96639. * @param url defines the url of the file to load
  96640. * @returns a new {BABYLON.ImageAssetTask} object
  96641. */
  96642. AssetsManager.prototype.addImageTask = function (taskName, url) {
  96643. var task = new ImageAssetTask(taskName, url);
  96644. this._tasks.push(task);
  96645. return task;
  96646. };
  96647. /**
  96648. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  96649. * @param taskName defines the name of the new task
  96650. * @param url defines the url of the file to load
  96651. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  96652. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  96653. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  96654. * @returns a new {BABYLON.TextureAssetTask} object
  96655. */
  96656. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  96657. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  96658. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  96659. this._tasks.push(task);
  96660. return task;
  96661. };
  96662. /**
  96663. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  96664. * @param taskName defines the name of the new task
  96665. * @param url defines the url of the file to load
  96666. * @param extensions defines the extension to use to load the cube map (can be null)
  96667. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  96668. * @param files defines the list of files to load (can be null)
  96669. * @returns a new {BABYLON.CubeTextureAssetTask} object
  96670. */
  96671. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  96672. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  96673. this._tasks.push(task);
  96674. return task;
  96675. };
  96676. /**
  96677. *
  96678. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  96679. * @param taskName defines the name of the new task
  96680. * @param url defines the url of the file to load
  96681. * @param size defines the size you want for the cubemap (can be null)
  96682. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  96683. * @param generateHarmonics defines if you want to automatically generate (true by default)
  96684. * @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)
  96685. * @param reserved Internal use only
  96686. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  96687. */
  96688. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  96689. if (noMipmap === void 0) { noMipmap = false; }
  96690. if (generateHarmonics === void 0) { generateHarmonics = true; }
  96691. if (gammaSpace === void 0) { gammaSpace = false; }
  96692. if (reserved === void 0) { reserved = false; }
  96693. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  96694. this._tasks.push(task);
  96695. return task;
  96696. };
  96697. /**
  96698. * Remove a task from the assets manager.
  96699. * @param task the task to remove
  96700. */
  96701. AssetsManager.prototype.removeTask = function (task) {
  96702. var index = this._tasks.indexOf(task);
  96703. if (index > -1) {
  96704. this._tasks.splice(index, 1);
  96705. }
  96706. };
  96707. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  96708. this._waitingTasksCount--;
  96709. try {
  96710. if (this.onProgress) {
  96711. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  96712. }
  96713. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  96714. }
  96715. catch (e) {
  96716. BABYLON.Tools.Error("Error running progress callbacks.");
  96717. console.log(e);
  96718. }
  96719. if (this._waitingTasksCount === 0) {
  96720. try {
  96721. if (this.onFinish) {
  96722. this.onFinish(this._tasks);
  96723. }
  96724. // Let's remove successfull tasks
  96725. var currentTasks = this._tasks.slice();
  96726. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  96727. var task = currentTasks_1[_i];
  96728. if (task.taskState === AssetTaskState.DONE) {
  96729. var index = this._tasks.indexOf(task);
  96730. if (index > -1) {
  96731. this._tasks.splice(index, 1);
  96732. }
  96733. }
  96734. }
  96735. this.onTasksDoneObservable.notifyObservers(this._tasks);
  96736. }
  96737. catch (e) {
  96738. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  96739. console.log(e);
  96740. }
  96741. this._isLoading = false;
  96742. this._scene.getEngine().hideLoadingUI();
  96743. }
  96744. };
  96745. AssetsManager.prototype._runTask = function (task) {
  96746. var _this = this;
  96747. var done = function () {
  96748. try {
  96749. if (_this.onTaskSuccess) {
  96750. _this.onTaskSuccess(task);
  96751. }
  96752. _this.onTaskSuccessObservable.notifyObservers(task);
  96753. _this._decreaseWaitingTasksCount(task);
  96754. }
  96755. catch (e) {
  96756. error("Error executing task success callbacks", e);
  96757. }
  96758. };
  96759. var error = function (message, exception) {
  96760. task._setErrorObject(message, exception);
  96761. if (_this.onTaskError) {
  96762. _this.onTaskError(task);
  96763. }
  96764. _this.onTaskErrorObservable.notifyObservers(task);
  96765. _this._decreaseWaitingTasksCount(task);
  96766. };
  96767. task.run(this._scene, done, error);
  96768. };
  96769. /**
  96770. * Reset the {BABYLON.AssetsManager} and remove all tasks
  96771. * @return the current instance of the {BABYLON.AssetsManager}
  96772. */
  96773. AssetsManager.prototype.reset = function () {
  96774. this._isLoading = false;
  96775. this._tasks = new Array();
  96776. return this;
  96777. };
  96778. /**
  96779. * Start the loading process
  96780. * @return the current instance of the {BABYLON.AssetsManager}
  96781. */
  96782. AssetsManager.prototype.load = function () {
  96783. if (this._isLoading) {
  96784. return this;
  96785. }
  96786. this._isLoading = true;
  96787. this._waitingTasksCount = this._tasks.length;
  96788. this._totalTasksCount = this._tasks.length;
  96789. if (this._waitingTasksCount === 0) {
  96790. this._isLoading = false;
  96791. if (this.onFinish) {
  96792. this.onFinish(this._tasks);
  96793. }
  96794. this.onTasksDoneObservable.notifyObservers(this._tasks);
  96795. return this;
  96796. }
  96797. if (this.useDefaultLoadingScreen) {
  96798. this._scene.getEngine().displayLoadingUI();
  96799. }
  96800. for (var index = 0; index < this._tasks.length; index++) {
  96801. var task = this._tasks[index];
  96802. if (task.taskState === AssetTaskState.INIT) {
  96803. this._runTask(task);
  96804. }
  96805. }
  96806. return this;
  96807. };
  96808. return AssetsManager;
  96809. }());
  96810. BABYLON.AssetsManager = AssetsManager;
  96811. })(BABYLON || (BABYLON = {}));
  96812. //# sourceMappingURL=babylon.assetsManager.js.map
  96813. var BABYLON;
  96814. (function (BABYLON) {
  96815. var serializedGeometries = [];
  96816. var serializeGeometry = function (geometry, serializationGeometries) {
  96817. if (serializedGeometries[geometry.id]) {
  96818. return;
  96819. }
  96820. if (geometry.doNotSerialize) {
  96821. return;
  96822. }
  96823. if (geometry instanceof BABYLON.BoxGeometry) {
  96824. serializationGeometries.boxes.push(geometry.serialize());
  96825. }
  96826. else if (geometry instanceof BABYLON.SphereGeometry) {
  96827. serializationGeometries.spheres.push(geometry.serialize());
  96828. }
  96829. else if (geometry instanceof BABYLON.CylinderGeometry) {
  96830. serializationGeometries.cylinders.push(geometry.serialize());
  96831. }
  96832. else if (geometry instanceof BABYLON.TorusGeometry) {
  96833. serializationGeometries.toruses.push(geometry.serialize());
  96834. }
  96835. else if (geometry instanceof BABYLON.GroundGeometry) {
  96836. serializationGeometries.grounds.push(geometry.serialize());
  96837. }
  96838. else if (geometry instanceof BABYLON.Plane) {
  96839. serializationGeometries.planes.push(geometry.serialize());
  96840. }
  96841. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  96842. serializationGeometries.torusKnots.push(geometry.serialize());
  96843. }
  96844. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  96845. throw new Error("Unknown primitive type");
  96846. }
  96847. else {
  96848. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  96849. }
  96850. serializedGeometries[geometry.id] = true;
  96851. };
  96852. var serializeMesh = function (mesh, serializationScene) {
  96853. var serializationObject = {};
  96854. // Geometry
  96855. var geometry = mesh._geometry;
  96856. if (geometry) {
  96857. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  96858. // 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
  96859. serializeGeometry(geometry, serializationScene.geometries);
  96860. }
  96861. }
  96862. // Custom
  96863. if (mesh.serialize) {
  96864. mesh.serialize(serializationObject);
  96865. }
  96866. return serializationObject;
  96867. };
  96868. var finalizeSingleMesh = function (mesh, serializationObject) {
  96869. //only works if the mesh is already loaded
  96870. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  96871. //serialize material
  96872. if (mesh.material) {
  96873. if (mesh.material instanceof BABYLON.MultiMaterial) {
  96874. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  96875. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  96876. serializationObject.multiMaterials.push(mesh.material.serialize());
  96877. }
  96878. }
  96879. else {
  96880. serializationObject.materials = serializationObject.materials || [];
  96881. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  96882. serializationObject.materials.push(mesh.material.serialize());
  96883. }
  96884. }
  96885. }
  96886. //serialize geometry
  96887. var geometry = mesh._geometry;
  96888. if (geometry) {
  96889. if (!serializationObject.geometries) {
  96890. serializationObject.geometries = {};
  96891. serializationObject.geometries.boxes = [];
  96892. serializationObject.geometries.spheres = [];
  96893. serializationObject.geometries.cylinders = [];
  96894. serializationObject.geometries.toruses = [];
  96895. serializationObject.geometries.grounds = [];
  96896. serializationObject.geometries.planes = [];
  96897. serializationObject.geometries.torusKnots = [];
  96898. serializationObject.geometries.vertexData = [];
  96899. }
  96900. serializeGeometry(geometry, serializationObject.geometries);
  96901. }
  96902. // Skeletons
  96903. if (mesh.skeleton) {
  96904. serializationObject.skeletons = serializationObject.skeletons || [];
  96905. serializationObject.skeletons.push(mesh.skeleton.serialize());
  96906. }
  96907. //serialize the actual mesh
  96908. serializationObject.meshes = serializationObject.meshes || [];
  96909. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  96910. }
  96911. };
  96912. var SceneSerializer = /** @class */ (function () {
  96913. function SceneSerializer() {
  96914. }
  96915. SceneSerializer.ClearCache = function () {
  96916. serializedGeometries = [];
  96917. };
  96918. SceneSerializer.Serialize = function (scene) {
  96919. var serializationObject = {};
  96920. SceneSerializer.ClearCache();
  96921. // Scene
  96922. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  96923. serializationObject.autoClear = scene.autoClear;
  96924. serializationObject.clearColor = scene.clearColor.asArray();
  96925. serializationObject.ambientColor = scene.ambientColor.asArray();
  96926. serializationObject.gravity = scene.gravity.asArray();
  96927. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  96928. serializationObject.workerCollisions = scene.workerCollisions;
  96929. // Fog
  96930. if (scene.fogMode && scene.fogMode !== 0) {
  96931. serializationObject.fogMode = scene.fogMode;
  96932. serializationObject.fogColor = scene.fogColor.asArray();
  96933. serializationObject.fogStart = scene.fogStart;
  96934. serializationObject.fogEnd = scene.fogEnd;
  96935. serializationObject.fogDensity = scene.fogDensity;
  96936. }
  96937. //Physics
  96938. if (scene.isPhysicsEnabled()) {
  96939. var physicEngine = scene.getPhysicsEngine();
  96940. if (physicEngine) {
  96941. serializationObject.physicsEnabled = true;
  96942. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  96943. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  96944. }
  96945. }
  96946. // Metadata
  96947. if (scene.metadata) {
  96948. serializationObject.metadata = scene.metadata;
  96949. }
  96950. // Morph targets
  96951. serializationObject.morphTargetManagers = [];
  96952. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  96953. var abstractMesh = _a[_i];
  96954. var manager = abstractMesh.morphTargetManager;
  96955. if (manager) {
  96956. serializationObject.morphTargetManagers.push(manager.serialize());
  96957. }
  96958. }
  96959. // Lights
  96960. serializationObject.lights = [];
  96961. var index;
  96962. var light;
  96963. for (index = 0; index < scene.lights.length; index++) {
  96964. light = scene.lights[index];
  96965. if (!light.doNotSerialize) {
  96966. serializationObject.lights.push(light.serialize());
  96967. }
  96968. }
  96969. // Cameras
  96970. serializationObject.cameras = [];
  96971. for (index = 0; index < scene.cameras.length; index++) {
  96972. var camera = scene.cameras[index];
  96973. if (!camera.doNotSerialize) {
  96974. serializationObject.cameras.push(camera.serialize());
  96975. }
  96976. }
  96977. if (scene.activeCamera) {
  96978. serializationObject.activeCameraID = scene.activeCamera.id;
  96979. }
  96980. // Animations
  96981. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  96982. // Materials
  96983. serializationObject.materials = [];
  96984. serializationObject.multiMaterials = [];
  96985. var material;
  96986. for (index = 0; index < scene.materials.length; index++) {
  96987. material = scene.materials[index];
  96988. if (!material.doNotSerialize) {
  96989. serializationObject.materials.push(material.serialize());
  96990. }
  96991. }
  96992. // MultiMaterials
  96993. serializationObject.multiMaterials = [];
  96994. for (index = 0; index < scene.multiMaterials.length; index++) {
  96995. var multiMaterial = scene.multiMaterials[index];
  96996. serializationObject.multiMaterials.push(multiMaterial.serialize());
  96997. }
  96998. // Environment texture
  96999. if (scene.environmentTexture) {
  97000. serializationObject.environmentTexture = scene.environmentTexture.name;
  97001. }
  97002. // Skeletons
  97003. serializationObject.skeletons = [];
  97004. for (index = 0; index < scene.skeletons.length; index++) {
  97005. var skeleton = scene.skeletons[index];
  97006. if (!skeleton.doNotSerialize) {
  97007. serializationObject.skeletons.push(skeleton.serialize());
  97008. }
  97009. }
  97010. // Transform nodes
  97011. serializationObject.transformNodes = [];
  97012. for (index = 0; index < scene.transformNodes.length; index++) {
  97013. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  97014. }
  97015. // Geometries
  97016. serializationObject.geometries = {};
  97017. serializationObject.geometries.boxes = [];
  97018. serializationObject.geometries.spheres = [];
  97019. serializationObject.geometries.cylinders = [];
  97020. serializationObject.geometries.toruses = [];
  97021. serializationObject.geometries.grounds = [];
  97022. serializationObject.geometries.planes = [];
  97023. serializationObject.geometries.torusKnots = [];
  97024. serializationObject.geometries.vertexData = [];
  97025. serializedGeometries = [];
  97026. var geometries = scene.getGeometries();
  97027. for (index = 0; index < geometries.length; index++) {
  97028. var geometry = geometries[index];
  97029. if (geometry.isReady()) {
  97030. serializeGeometry(geometry, serializationObject.geometries);
  97031. }
  97032. }
  97033. // Meshes
  97034. serializationObject.meshes = [];
  97035. for (index = 0; index < scene.meshes.length; index++) {
  97036. var abstractMesh = scene.meshes[index];
  97037. if (abstractMesh instanceof BABYLON.Mesh) {
  97038. var mesh = abstractMesh;
  97039. if (!mesh.doNotSerialize) {
  97040. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  97041. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  97042. }
  97043. }
  97044. }
  97045. }
  97046. // Particles Systems
  97047. serializationObject.particleSystems = [];
  97048. for (index = 0; index < scene.particleSystems.length; index++) {
  97049. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  97050. }
  97051. // Lens flares
  97052. serializationObject.lensFlareSystems = [];
  97053. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  97054. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  97055. }
  97056. // Shadows
  97057. serializationObject.shadowGenerators = [];
  97058. for (index = 0; index < scene.lights.length; index++) {
  97059. light = scene.lights[index];
  97060. var shadowGenerator = light.getShadowGenerator();
  97061. if (shadowGenerator) {
  97062. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  97063. }
  97064. }
  97065. // Action Manager
  97066. if (scene.actionManager) {
  97067. serializationObject.actions = scene.actionManager.serialize("scene");
  97068. }
  97069. // Audio
  97070. serializationObject.sounds = [];
  97071. for (index = 0; index < scene.soundTracks.length; index++) {
  97072. var soundtrack = scene.soundTracks[index];
  97073. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  97074. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  97075. }
  97076. }
  97077. // Effect layers
  97078. serializationObject.effectLayers = [];
  97079. for (index = 0; index < scene.effectLayers.length; index++) {
  97080. var layer = scene.effectLayers[index];
  97081. if (layer.serialize) {
  97082. serializationObject.effectLayers.push(layer.serialize());
  97083. }
  97084. }
  97085. return serializationObject;
  97086. };
  97087. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  97088. if (withParents === void 0) { withParents = false; }
  97089. if (withChildren === void 0) { withChildren = false; }
  97090. var serializationObject = {};
  97091. SceneSerializer.ClearCache();
  97092. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  97093. if (withParents || withChildren) {
  97094. //deliberate for loop! not for each, appended should be processed as well.
  97095. for (var i = 0; i < toSerialize.length; ++i) {
  97096. if (withChildren) {
  97097. toSerialize[i].getDescendants().forEach(function (node) {
  97098. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  97099. toSerialize.push(node);
  97100. }
  97101. });
  97102. }
  97103. //make sure the array doesn't contain the object already
  97104. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  97105. toSerialize.push(toSerialize[i].parent);
  97106. }
  97107. }
  97108. }
  97109. toSerialize.forEach(function (mesh) {
  97110. finalizeSingleMesh(mesh, serializationObject);
  97111. });
  97112. return serializationObject;
  97113. };
  97114. return SceneSerializer;
  97115. }());
  97116. BABYLON.SceneSerializer = SceneSerializer;
  97117. })(BABYLON || (BABYLON = {}));
  97118. //# sourceMappingURL=babylon.sceneSerializer.js.map
  97119. var BABYLON;
  97120. (function (BABYLON) {
  97121. var ReflectionProbe = /** @class */ (function () {
  97122. function ReflectionProbe(name, size, scene, generateMipMaps) {
  97123. if (generateMipMaps === void 0) { generateMipMaps = true; }
  97124. var _this = this;
  97125. this.name = name;
  97126. this._viewMatrix = BABYLON.Matrix.Identity();
  97127. this._target = BABYLON.Vector3.Zero();
  97128. this._add = BABYLON.Vector3.Zero();
  97129. this._invertYAxis = false;
  97130. this.position = BABYLON.Vector3.Zero();
  97131. this._scene = scene;
  97132. this._scene.reflectionProbes.push(this);
  97133. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  97134. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  97135. switch (faceIndex) {
  97136. case 0:
  97137. _this._add.copyFromFloats(1, 0, 0);
  97138. break;
  97139. case 1:
  97140. _this._add.copyFromFloats(-1, 0, 0);
  97141. break;
  97142. case 2:
  97143. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  97144. break;
  97145. case 3:
  97146. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  97147. break;
  97148. case 4:
  97149. _this._add.copyFromFloats(0, 0, 1);
  97150. break;
  97151. case 5:
  97152. _this._add.copyFromFloats(0, 0, -1);
  97153. break;
  97154. }
  97155. if (_this._attachedMesh) {
  97156. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  97157. }
  97158. _this.position.addToRef(_this._add, _this._target);
  97159. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  97160. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  97161. scene._forcedViewPosition = _this.position;
  97162. });
  97163. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  97164. scene._forcedViewPosition = null;
  97165. scene.updateTransformMatrix(true);
  97166. });
  97167. if (scene.activeCamera) {
  97168. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  97169. }
  97170. }
  97171. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  97172. get: function () {
  97173. return this._renderTargetTexture.samples;
  97174. },
  97175. set: function (value) {
  97176. this._renderTargetTexture.samples = value;
  97177. },
  97178. enumerable: true,
  97179. configurable: true
  97180. });
  97181. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  97182. get: function () {
  97183. return this._renderTargetTexture.refreshRate;
  97184. },
  97185. set: function (value) {
  97186. this._renderTargetTexture.refreshRate = value;
  97187. },
  97188. enumerable: true,
  97189. configurable: true
  97190. });
  97191. ReflectionProbe.prototype.getScene = function () {
  97192. return this._scene;
  97193. };
  97194. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  97195. get: function () {
  97196. return this._renderTargetTexture;
  97197. },
  97198. enumerable: true,
  97199. configurable: true
  97200. });
  97201. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  97202. get: function () {
  97203. return this._renderTargetTexture.renderList;
  97204. },
  97205. enumerable: true,
  97206. configurable: true
  97207. });
  97208. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  97209. this._attachedMesh = mesh;
  97210. };
  97211. /**
  97212. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  97213. *
  97214. * @param renderingGroupId The rendering group id corresponding to its index
  97215. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  97216. */
  97217. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  97218. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  97219. };
  97220. ReflectionProbe.prototype.dispose = function () {
  97221. var index = this._scene.reflectionProbes.indexOf(this);
  97222. if (index !== -1) {
  97223. // Remove from the scene if found
  97224. this._scene.reflectionProbes.splice(index, 1);
  97225. }
  97226. if (this._renderTargetTexture) {
  97227. this._renderTargetTexture.dispose();
  97228. this._renderTargetTexture = null;
  97229. }
  97230. };
  97231. return ReflectionProbe;
  97232. }());
  97233. BABYLON.ReflectionProbe = ReflectionProbe;
  97234. })(BABYLON || (BABYLON = {}));
  97235. //# sourceMappingURL=babylon.reflectionProbe.js.map
  97236. var BABYLON;
  97237. (function (BABYLON) {
  97238. var Layer = /** @class */ (function () {
  97239. function Layer(name, imgUrl, scene, isBackground, color) {
  97240. this.name = name;
  97241. this.scale = new BABYLON.Vector2(1, 1);
  97242. this.offset = new BABYLON.Vector2(0, 0);
  97243. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  97244. this.layerMask = 0x0FFFFFFF;
  97245. this._vertexBuffers = {};
  97246. // Events
  97247. /**
  97248. * An event triggered when the layer is disposed.
  97249. */
  97250. this.onDisposeObservable = new BABYLON.Observable();
  97251. /**
  97252. * An event triggered before rendering the scene
  97253. */
  97254. this.onBeforeRenderObservable = new BABYLON.Observable();
  97255. /**
  97256. * An event triggered after rendering the scene
  97257. */
  97258. this.onAfterRenderObservable = new BABYLON.Observable();
  97259. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  97260. this.isBackground = isBackground === undefined ? true : isBackground;
  97261. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  97262. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  97263. this._scene.layers.push(this);
  97264. var engine = this._scene.getEngine();
  97265. // VBO
  97266. var vertices = [];
  97267. vertices.push(1, 1);
  97268. vertices.push(-1, 1);
  97269. vertices.push(-1, -1);
  97270. vertices.push(1, -1);
  97271. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  97272. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  97273. this._createIndexBuffer();
  97274. // Effects
  97275. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  97276. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  97277. }
  97278. Object.defineProperty(Layer.prototype, "onDispose", {
  97279. set: function (callback) {
  97280. if (this._onDisposeObserver) {
  97281. this.onDisposeObservable.remove(this._onDisposeObserver);
  97282. }
  97283. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  97284. },
  97285. enumerable: true,
  97286. configurable: true
  97287. });
  97288. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  97289. set: function (callback) {
  97290. if (this._onBeforeRenderObserver) {
  97291. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  97292. }
  97293. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  97294. },
  97295. enumerable: true,
  97296. configurable: true
  97297. });
  97298. Object.defineProperty(Layer.prototype, "onAfterRender", {
  97299. set: function (callback) {
  97300. if (this._onAfterRenderObserver) {
  97301. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  97302. }
  97303. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  97304. },
  97305. enumerable: true,
  97306. configurable: true
  97307. });
  97308. Layer.prototype._createIndexBuffer = function () {
  97309. var engine = this._scene.getEngine();
  97310. // Indices
  97311. var indices = [];
  97312. indices.push(0);
  97313. indices.push(1);
  97314. indices.push(2);
  97315. indices.push(0);
  97316. indices.push(2);
  97317. indices.push(3);
  97318. this._indexBuffer = engine.createIndexBuffer(indices);
  97319. };
  97320. Layer.prototype._rebuild = function () {
  97321. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  97322. if (vb) {
  97323. vb._rebuild();
  97324. }
  97325. this._createIndexBuffer();
  97326. };
  97327. Layer.prototype.render = function () {
  97328. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  97329. // Check
  97330. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  97331. return;
  97332. var engine = this._scene.getEngine();
  97333. this.onBeforeRenderObservable.notifyObservers(this);
  97334. // Render
  97335. engine.enableEffect(currentEffect);
  97336. engine.setState(false);
  97337. // Texture
  97338. currentEffect.setTexture("textureSampler", this.texture);
  97339. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  97340. // Color
  97341. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  97342. // Scale / offset
  97343. currentEffect.setVector2("offset", this.offset);
  97344. currentEffect.setVector2("scale", this.scale);
  97345. // VBOs
  97346. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  97347. // Draw order
  97348. if (!this.alphaTest) {
  97349. engine.setAlphaMode(this.alphaBlendingMode);
  97350. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97351. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  97352. }
  97353. else {
  97354. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97355. }
  97356. this.onAfterRenderObservable.notifyObservers(this);
  97357. };
  97358. Layer.prototype.dispose = function () {
  97359. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  97360. if (vertexBuffer) {
  97361. vertexBuffer.dispose();
  97362. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  97363. }
  97364. if (this._indexBuffer) {
  97365. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  97366. this._indexBuffer = null;
  97367. }
  97368. if (this.texture) {
  97369. this.texture.dispose();
  97370. this.texture = null;
  97371. }
  97372. // Remove from scene
  97373. var index = this._scene.layers.indexOf(this);
  97374. this._scene.layers.splice(index, 1);
  97375. // Callback
  97376. this.onDisposeObservable.notifyObservers(this);
  97377. this.onDisposeObservable.clear();
  97378. this.onAfterRenderObservable.clear();
  97379. this.onBeforeRenderObservable.clear();
  97380. };
  97381. return Layer;
  97382. }());
  97383. BABYLON.Layer = Layer;
  97384. })(BABYLON || (BABYLON = {}));
  97385. //# sourceMappingURL=babylon.layer.js.map
  97386. var BABYLON;
  97387. (function (BABYLON) {
  97388. var TextureTools = /** @class */ (function () {
  97389. function TextureTools() {
  97390. }
  97391. /**
  97392. * Uses the GPU to create a copy texture rescaled at a given size
  97393. * @param texture Texture to copy from
  97394. * @param width Desired width
  97395. * @param height Desired height
  97396. * @return Generated texture
  97397. */
  97398. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  97399. if (useBilinearMode === void 0) { useBilinearMode = true; }
  97400. var scene = texture.getScene();
  97401. var engine = scene.getEngine();
  97402. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  97403. rtt.wrapU = texture.wrapU;
  97404. rtt.wrapV = texture.wrapV;
  97405. rtt.uOffset = texture.uOffset;
  97406. rtt.vOffset = texture.vOffset;
  97407. rtt.uScale = texture.uScale;
  97408. rtt.vScale = texture.vScale;
  97409. rtt.uAng = texture.uAng;
  97410. rtt.vAng = texture.vAng;
  97411. rtt.wAng = texture.wAng;
  97412. rtt.coordinatesIndex = texture.coordinatesIndex;
  97413. rtt.level = texture.level;
  97414. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  97415. rtt._texture.isReady = false;
  97416. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97417. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97418. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  97419. passPostProcess.getEffect().executeWhenCompiled(function () {
  97420. passPostProcess.onApply = function (effect) {
  97421. effect.setTexture("textureSampler", texture);
  97422. };
  97423. var internalTexture = rtt.getInternalTexture();
  97424. if (internalTexture) {
  97425. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  97426. engine.unBindFramebuffer(internalTexture);
  97427. rtt.disposeFramebufferObjects();
  97428. passPostProcess.dispose();
  97429. internalTexture.isReady = true;
  97430. }
  97431. });
  97432. return rtt;
  97433. };
  97434. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  97435. if (!scene._environmentBRDFTexture) {
  97436. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  97437. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97438. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97439. scene._environmentBRDFTexture = texture;
  97440. }
  97441. return scene._environmentBRDFTexture;
  97442. };
  97443. 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=";
  97444. return TextureTools;
  97445. }());
  97446. BABYLON.TextureTools = TextureTools;
  97447. })(BABYLON || (BABYLON = {}));
  97448. //# sourceMappingURL=babylon.textureTools.js.map
  97449. var BABYLON;
  97450. (function (BABYLON) {
  97451. var FramingBehavior = /** @class */ (function () {
  97452. function FramingBehavior() {
  97453. this._mode = FramingBehavior.FitFrustumSidesMode;
  97454. this._radiusScale = 1.0;
  97455. this._positionScale = 0.5;
  97456. this._defaultElevation = 0.3;
  97457. this._elevationReturnTime = 1500;
  97458. this._elevationReturnWaitTime = 1000;
  97459. this._zoomStopsAnimation = false;
  97460. this._framingTime = 1500;
  97461. this._isPointerDown = false;
  97462. this._lastInteractionTime = -Infinity;
  97463. // Framing control
  97464. this._animatables = new Array();
  97465. this._betaIsAnimating = false;
  97466. }
  97467. Object.defineProperty(FramingBehavior.prototype, "name", {
  97468. get: function () {
  97469. return "Framing";
  97470. },
  97471. enumerable: true,
  97472. configurable: true
  97473. });
  97474. Object.defineProperty(FramingBehavior.prototype, "mode", {
  97475. /**
  97476. * Gets current mode used by the behavior.
  97477. */
  97478. get: function () {
  97479. return this._mode;
  97480. },
  97481. /**
  97482. * Sets the current mode used by the behavior
  97483. */
  97484. set: function (mode) {
  97485. this._mode = mode;
  97486. },
  97487. enumerable: true,
  97488. configurable: true
  97489. });
  97490. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  97491. /**
  97492. * Gets the scale applied to the radius
  97493. */
  97494. get: function () {
  97495. return this._radiusScale;
  97496. },
  97497. /**
  97498. * Sets the scale applied to the radius (1 by default)
  97499. */
  97500. set: function (radius) {
  97501. this._radiusScale = radius;
  97502. },
  97503. enumerable: true,
  97504. configurable: true
  97505. });
  97506. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  97507. /**
  97508. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  97509. */
  97510. get: function () {
  97511. return this._positionScale;
  97512. },
  97513. /**
  97514. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  97515. */
  97516. set: function (scale) {
  97517. this._positionScale = scale;
  97518. },
  97519. enumerable: true,
  97520. configurable: true
  97521. });
  97522. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  97523. /**
  97524. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  97525. * behaviour is triggered, in radians.
  97526. */
  97527. get: function () {
  97528. return this._defaultElevation;
  97529. },
  97530. /**
  97531. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  97532. * behaviour is triggered, in radians.
  97533. */
  97534. set: function (elevation) {
  97535. this._defaultElevation = elevation;
  97536. },
  97537. enumerable: true,
  97538. configurable: true
  97539. });
  97540. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  97541. /**
  97542. * Gets the time (in milliseconds) taken to return to the default beta position.
  97543. * Negative value indicates camera should not return to default.
  97544. */
  97545. get: function () {
  97546. return this._elevationReturnTime;
  97547. },
  97548. /**
  97549. * Sets the time (in milliseconds) taken to return to the default beta position.
  97550. * Negative value indicates camera should not return to default.
  97551. */
  97552. set: function (speed) {
  97553. this._elevationReturnTime = speed;
  97554. },
  97555. enumerable: true,
  97556. configurable: true
  97557. });
  97558. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  97559. /**
  97560. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  97561. */
  97562. get: function () {
  97563. return this._elevationReturnWaitTime;
  97564. },
  97565. /**
  97566. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  97567. */
  97568. set: function (time) {
  97569. this._elevationReturnWaitTime = time;
  97570. },
  97571. enumerable: true,
  97572. configurable: true
  97573. });
  97574. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  97575. /**
  97576. * Gets the flag that indicates if user zooming should stop animation.
  97577. */
  97578. get: function () {
  97579. return this._zoomStopsAnimation;
  97580. },
  97581. /**
  97582. * Sets the flag that indicates if user zooming should stop animation.
  97583. */
  97584. set: function (flag) {
  97585. this._zoomStopsAnimation = flag;
  97586. },
  97587. enumerable: true,
  97588. configurable: true
  97589. });
  97590. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  97591. /**
  97592. * Gets the transition time when framing the mesh, in milliseconds
  97593. */
  97594. get: function () {
  97595. return this._framingTime;
  97596. },
  97597. /**
  97598. * Sets the transition time when framing the mesh, in milliseconds
  97599. */
  97600. set: function (time) {
  97601. this._framingTime = time;
  97602. },
  97603. enumerable: true,
  97604. configurable: true
  97605. });
  97606. FramingBehavior.prototype.init = function () {
  97607. // Do notihng
  97608. };
  97609. FramingBehavior.prototype.attach = function (camera) {
  97610. var _this = this;
  97611. this._attachedCamera = camera;
  97612. var scene = this._attachedCamera.getScene();
  97613. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  97614. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  97615. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  97616. _this._isPointerDown = true;
  97617. return;
  97618. }
  97619. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  97620. _this._isPointerDown = false;
  97621. }
  97622. });
  97623. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  97624. if (mesh) {
  97625. _this.zoomOnMesh(mesh);
  97626. }
  97627. });
  97628. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  97629. // Stop the animation if there is user interaction and the animation should stop for this interaction
  97630. _this._applyUserInteraction();
  97631. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  97632. // back to the default position after a given timeout
  97633. _this._maintainCameraAboveGround();
  97634. });
  97635. };
  97636. FramingBehavior.prototype.detach = function () {
  97637. if (!this._attachedCamera) {
  97638. return;
  97639. }
  97640. var scene = this._attachedCamera.getScene();
  97641. if (this._onPrePointerObservableObserver) {
  97642. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  97643. }
  97644. if (this._onAfterCheckInputsObserver) {
  97645. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  97646. }
  97647. if (this._onMeshTargetChangedObserver) {
  97648. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  97649. }
  97650. this._attachedCamera = null;
  97651. };
  97652. /**
  97653. * Targets the given mesh and updates zoom level accordingly.
  97654. * @param mesh The mesh to target.
  97655. * @param radius Optional. If a cached radius position already exists, overrides default.
  97656. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  97657. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  97658. * @param onAnimationEnd Callback triggered at the end of the framing animation
  97659. */
  97660. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  97661. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  97662. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  97663. mesh.computeWorldMatrix(true);
  97664. var boundingBox = mesh.getBoundingInfo().boundingBox;
  97665. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  97666. };
  97667. /**
  97668. * Targets the given mesh with its children and updates zoom level accordingly.
  97669. * @param mesh The mesh to target.
  97670. * @param radius Optional. If a cached radius position already exists, overrides default.
  97671. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  97672. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  97673. * @param onAnimationEnd Callback triggered at the end of the framing animation
  97674. */
  97675. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  97676. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  97677. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  97678. mesh.computeWorldMatrix(true);
  97679. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  97680. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  97681. };
  97682. /**
  97683. * Targets the given meshes with their children and updates zoom level accordingly.
  97684. * @param meshes The mesh to target.
  97685. * @param radius Optional. If a cached radius position already exists, overrides default.
  97686. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  97687. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  97688. * @param onAnimationEnd Callback triggered at the end of the framing animation
  97689. */
  97690. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  97691. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  97692. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  97693. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  97694. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  97695. for (var i = 0; i < meshes.length; i++) {
  97696. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  97697. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  97698. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  97699. }
  97700. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  97701. };
  97702. /**
  97703. * Targets the given mesh and updates zoom level accordingly.
  97704. * @param mesh The mesh to target.
  97705. * @param radius Optional. If a cached radius position already exists, overrides default.
  97706. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  97707. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  97708. * @param onAnimationEnd Callback triggered at the end of the framing animation
  97709. */
  97710. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  97711. var _this = this;
  97712. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  97713. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  97714. var zoomTarget;
  97715. if (!this._attachedCamera) {
  97716. return;
  97717. }
  97718. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  97719. var bottom = minimumWorld.y;
  97720. var top = maximumWorld.y;
  97721. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  97722. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  97723. if (focusOnOriginXZ) {
  97724. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  97725. }
  97726. else {
  97727. var centerWorld = minimumWorld.add(radiusWorld);
  97728. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  97729. }
  97730. if (!this._vectorTransition) {
  97731. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  97732. }
  97733. this._betaIsAnimating = true;
  97734. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  97735. if (animatable) {
  97736. this._animatables.push(animatable);
  97737. }
  97738. // sets the radius and lower radius bounds
  97739. // Small delta ensures camera is not always at lower zoom limit.
  97740. var radius = 0;
  97741. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  97742. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  97743. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  97744. radius = position;
  97745. }
  97746. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  97747. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  97748. if (this._attachedCamera.lowerRadiusLimit === null) {
  97749. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  97750. }
  97751. }
  97752. // Set sensibilities
  97753. var extend = maximumWorld.subtract(minimumWorld).length();
  97754. this._attachedCamera.panningSensibility = 5000 / extend;
  97755. this._attachedCamera.wheelPrecision = 100 / radius;
  97756. // transition to new radius
  97757. if (!this._radiusTransition) {
  97758. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  97759. }
  97760. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  97761. _this.stopAllAnimations();
  97762. if (onAnimationEnd) {
  97763. onAnimationEnd();
  97764. }
  97765. if (_this._attachedCamera) {
  97766. _this._attachedCamera.storeState();
  97767. }
  97768. });
  97769. if (animatable) {
  97770. this._animatables.push(animatable);
  97771. }
  97772. };
  97773. /**
  97774. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  97775. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  97776. * frustum width.
  97777. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  97778. * to fully enclose the mesh in the viewing frustum.
  97779. */
  97780. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  97781. var size = maximumWorld.subtract(minimumWorld);
  97782. var boxVectorGlobalDiagonal = size.length();
  97783. var frustumSlope = this._getFrustumSlope();
  97784. // Formula for setting distance
  97785. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  97786. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  97787. // Horizon distance
  97788. var radius = radiusWithoutFraming * this._radiusScale;
  97789. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  97790. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  97791. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  97792. var camera = this._attachedCamera;
  97793. if (!camera) {
  97794. return 0;
  97795. }
  97796. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  97797. // Don't exceed the requested limit
  97798. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  97799. }
  97800. // Don't exceed the upper radius limit
  97801. if (camera.upperRadiusLimit) {
  97802. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  97803. }
  97804. return distance;
  97805. };
  97806. /**
  97807. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  97808. * is automatically returned to its default position (expected to be above ground plane).
  97809. */
  97810. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  97811. var _this = this;
  97812. if (this._elevationReturnTime < 0) {
  97813. return;
  97814. }
  97815. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  97816. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  97817. var limitBeta = Math.PI * 0.5;
  97818. // Bring the camera back up if below the ground plane
  97819. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  97820. this._betaIsAnimating = true;
  97821. //Transition to new position
  97822. this.stopAllAnimations();
  97823. if (!this._betaTransition) {
  97824. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  97825. }
  97826. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  97827. _this._clearAnimationLocks();
  97828. _this.stopAllAnimations();
  97829. });
  97830. if (animatabe) {
  97831. this._animatables.push(animatabe);
  97832. }
  97833. }
  97834. };
  97835. /**
  97836. * Returns the frustum slope based on the canvas ratio and camera FOV
  97837. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  97838. */
  97839. FramingBehavior.prototype._getFrustumSlope = function () {
  97840. // Calculate the viewport ratio
  97841. // Aspect Ratio is Height/Width.
  97842. var camera = this._attachedCamera;
  97843. if (!camera) {
  97844. return BABYLON.Vector2.Zero();
  97845. }
  97846. var engine = camera.getScene().getEngine();
  97847. var aspectRatio = engine.getAspectRatio(camera);
  97848. // Camera FOV is the vertical field of view (top-bottom) in radians.
  97849. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  97850. var frustumSlopeY = Math.tan(camera.fov / 2);
  97851. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  97852. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  97853. // along the forward vector.
  97854. var frustumSlopeX = frustumSlopeY * aspectRatio;
  97855. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  97856. };
  97857. /**
  97858. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  97859. */
  97860. FramingBehavior.prototype._clearAnimationLocks = function () {
  97861. this._betaIsAnimating = false;
  97862. };
  97863. /**
  97864. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  97865. */
  97866. FramingBehavior.prototype._applyUserInteraction = function () {
  97867. if (this.isUserIsMoving) {
  97868. this._lastInteractionTime = BABYLON.Tools.Now;
  97869. this.stopAllAnimations();
  97870. this._clearAnimationLocks();
  97871. }
  97872. };
  97873. /**
  97874. * Stops and removes all animations that have been applied to the camera
  97875. */
  97876. FramingBehavior.prototype.stopAllAnimations = function () {
  97877. if (this._attachedCamera) {
  97878. this._attachedCamera.animations = [];
  97879. }
  97880. while (this._animatables.length) {
  97881. if (this._animatables[0]) {
  97882. this._animatables[0].onAnimationEnd = null;
  97883. this._animatables[0].stop();
  97884. }
  97885. this._animatables.shift();
  97886. }
  97887. };
  97888. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  97889. /**
  97890. * Gets a value indicating if the user is moving the camera
  97891. */
  97892. get: function () {
  97893. if (!this._attachedCamera) {
  97894. return false;
  97895. }
  97896. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  97897. this._attachedCamera.inertialBetaOffset !== 0 ||
  97898. this._attachedCamera.inertialRadiusOffset !== 0 ||
  97899. this._attachedCamera.inertialPanningX !== 0 ||
  97900. this._attachedCamera.inertialPanningY !== 0 ||
  97901. this._isPointerDown;
  97902. },
  97903. enumerable: true,
  97904. configurable: true
  97905. });
  97906. /**
  97907. * The easing function used by animations
  97908. */
  97909. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  97910. /**
  97911. * The easing mode used by animations
  97912. */
  97913. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  97914. // Statics
  97915. /**
  97916. * The camera can move all the way towards the mesh.
  97917. */
  97918. FramingBehavior.IgnoreBoundsSizeMode = 0;
  97919. /**
  97920. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  97921. */
  97922. FramingBehavior.FitFrustumSidesMode = 1;
  97923. return FramingBehavior;
  97924. }());
  97925. BABYLON.FramingBehavior = FramingBehavior;
  97926. })(BABYLON || (BABYLON = {}));
  97927. //# sourceMappingURL=babylon.framingBehavior.js.map
  97928. var BABYLON;
  97929. (function (BABYLON) {
  97930. /**
  97931. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  97932. */
  97933. var BouncingBehavior = /** @class */ (function () {
  97934. function BouncingBehavior() {
  97935. /**
  97936. * The duration of the animation, in milliseconds
  97937. */
  97938. this.transitionDuration = 450;
  97939. /**
  97940. * Length of the distance animated by the transition when lower radius is reached
  97941. */
  97942. this.lowerRadiusTransitionRange = 2;
  97943. /**
  97944. * Length of the distance animated by the transition when upper radius is reached
  97945. */
  97946. this.upperRadiusTransitionRange = -2;
  97947. this._autoTransitionRange = false;
  97948. // Animations
  97949. this._radiusIsAnimating = false;
  97950. this._radiusBounceTransition = null;
  97951. this._animatables = new Array();
  97952. }
  97953. Object.defineProperty(BouncingBehavior.prototype, "name", {
  97954. get: function () {
  97955. return "Bouncing";
  97956. },
  97957. enumerable: true,
  97958. configurable: true
  97959. });
  97960. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  97961. /**
  97962. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  97963. */
  97964. get: function () {
  97965. return this._autoTransitionRange;
  97966. },
  97967. /**
  97968. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  97969. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  97970. */
  97971. set: function (value) {
  97972. var _this = this;
  97973. if (this._autoTransitionRange === value) {
  97974. return;
  97975. }
  97976. this._autoTransitionRange = value;
  97977. var camera = this._attachedCamera;
  97978. if (!camera) {
  97979. return;
  97980. }
  97981. if (value) {
  97982. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  97983. if (!mesh) {
  97984. return;
  97985. }
  97986. mesh.computeWorldMatrix(true);
  97987. var diagonal = mesh.getBoundingInfo().diagonalLength;
  97988. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  97989. _this.upperRadiusTransitionRange = diagonal * 0.05;
  97990. });
  97991. }
  97992. else if (this._onMeshTargetChangedObserver) {
  97993. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  97994. }
  97995. },
  97996. enumerable: true,
  97997. configurable: true
  97998. });
  97999. BouncingBehavior.prototype.init = function () {
  98000. // Do notihng
  98001. };
  98002. BouncingBehavior.prototype.attach = function (camera) {
  98003. var _this = this;
  98004. this._attachedCamera = camera;
  98005. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  98006. if (!_this._attachedCamera) {
  98007. return;
  98008. }
  98009. // Add the bounce animation to the lower radius limit
  98010. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  98011. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  98012. }
  98013. // Add the bounce animation to the upper radius limit
  98014. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  98015. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  98016. }
  98017. });
  98018. };
  98019. BouncingBehavior.prototype.detach = function () {
  98020. if (!this._attachedCamera) {
  98021. return;
  98022. }
  98023. if (this._onAfterCheckInputsObserver) {
  98024. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  98025. }
  98026. if (this._onMeshTargetChangedObserver) {
  98027. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  98028. }
  98029. this._attachedCamera = null;
  98030. };
  98031. /**
  98032. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  98033. * @param radiusLimit The limit to check against.
  98034. * @return Bool to indicate if at limit.
  98035. */
  98036. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  98037. if (!this._attachedCamera) {
  98038. return false;
  98039. }
  98040. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  98041. return true;
  98042. }
  98043. return false;
  98044. };
  98045. /**
  98046. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  98047. * @param radiusDelta The delta by which to animate to. Can be negative.
  98048. */
  98049. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  98050. var _this = this;
  98051. if (!this._attachedCamera) {
  98052. return;
  98053. }
  98054. if (!this._radiusBounceTransition) {
  98055. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  98056. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  98057. }
  98058. // Prevent zoom until bounce has completed
  98059. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  98060. this._attachedCamera.wheelPrecision = Infinity;
  98061. this._attachedCamera.inertialRadiusOffset = 0;
  98062. // Animate to the radius limit
  98063. this.stopAllAnimations();
  98064. this._radiusIsAnimating = true;
  98065. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  98066. if (animatable) {
  98067. this._animatables.push(animatable);
  98068. }
  98069. };
  98070. /**
  98071. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  98072. */
  98073. BouncingBehavior.prototype._clearAnimationLocks = function () {
  98074. this._radiusIsAnimating = false;
  98075. if (this._attachedCamera) {
  98076. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  98077. }
  98078. };
  98079. /**
  98080. * Stops and removes all animations that have been applied to the camera
  98081. */
  98082. BouncingBehavior.prototype.stopAllAnimations = function () {
  98083. if (this._attachedCamera) {
  98084. this._attachedCamera.animations = [];
  98085. }
  98086. while (this._animatables.length) {
  98087. this._animatables[0].onAnimationEnd = null;
  98088. this._animatables[0].stop();
  98089. this._animatables.shift();
  98090. }
  98091. };
  98092. /**
  98093. * The easing function used by animations
  98094. */
  98095. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  98096. /**
  98097. * The easing mode used by animations
  98098. */
  98099. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  98100. return BouncingBehavior;
  98101. }());
  98102. BABYLON.BouncingBehavior = BouncingBehavior;
  98103. })(BABYLON || (BABYLON = {}));
  98104. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  98105. var BABYLON;
  98106. (function (BABYLON) {
  98107. var AutoRotationBehavior = /** @class */ (function () {
  98108. function AutoRotationBehavior() {
  98109. this._zoomStopsAnimation = false;
  98110. this._idleRotationSpeed = 0.05;
  98111. this._idleRotationWaitTime = 2000;
  98112. this._idleRotationSpinupTime = 2000;
  98113. this._isPointerDown = false;
  98114. this._lastFrameTime = null;
  98115. this._lastInteractionTime = -Infinity;
  98116. this._cameraRotationSpeed = 0;
  98117. this._lastFrameRadius = 0;
  98118. }
  98119. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  98120. get: function () {
  98121. return "AutoRotation";
  98122. },
  98123. enumerable: true,
  98124. configurable: true
  98125. });
  98126. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  98127. /**
  98128. * Gets the flag that indicates if user zooming should stop animation.
  98129. */
  98130. get: function () {
  98131. return this._zoomStopsAnimation;
  98132. },
  98133. /**
  98134. * Sets the flag that indicates if user zooming should stop animation.
  98135. */
  98136. set: function (flag) {
  98137. this._zoomStopsAnimation = flag;
  98138. },
  98139. enumerable: true,
  98140. configurable: true
  98141. });
  98142. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  98143. /**
  98144. * Gets the default speed at which the camera rotates around the model.
  98145. */
  98146. get: function () {
  98147. return this._idleRotationSpeed;
  98148. },
  98149. /**
  98150. * Sets the default speed at which the camera rotates around the model.
  98151. */
  98152. set: function (speed) {
  98153. this._idleRotationSpeed = speed;
  98154. },
  98155. enumerable: true,
  98156. configurable: true
  98157. });
  98158. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  98159. /**
  98160. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  98161. */
  98162. get: function () {
  98163. return this._idleRotationWaitTime;
  98164. },
  98165. /**
  98166. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  98167. */
  98168. set: function (time) {
  98169. this._idleRotationWaitTime = time;
  98170. },
  98171. enumerable: true,
  98172. configurable: true
  98173. });
  98174. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  98175. /**
  98176. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  98177. */
  98178. get: function () {
  98179. return this._idleRotationSpinupTime;
  98180. },
  98181. /**
  98182. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  98183. */
  98184. set: function (time) {
  98185. this._idleRotationSpinupTime = time;
  98186. },
  98187. enumerable: true,
  98188. configurable: true
  98189. });
  98190. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  98191. /**
  98192. * Gets a value indicating if the camera is currently rotating because of this behavior
  98193. */
  98194. get: function () {
  98195. return Math.abs(this._cameraRotationSpeed) > 0;
  98196. },
  98197. enumerable: true,
  98198. configurable: true
  98199. });
  98200. AutoRotationBehavior.prototype.init = function () {
  98201. // Do notihng
  98202. };
  98203. AutoRotationBehavior.prototype.attach = function (camera) {
  98204. var _this = this;
  98205. this._attachedCamera = camera;
  98206. var scene = this._attachedCamera.getScene();
  98207. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  98208. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  98209. _this._isPointerDown = true;
  98210. return;
  98211. }
  98212. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  98213. _this._isPointerDown = false;
  98214. }
  98215. });
  98216. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  98217. var now = BABYLON.Tools.Now;
  98218. var dt = 0;
  98219. if (_this._lastFrameTime != null) {
  98220. dt = now - _this._lastFrameTime;
  98221. }
  98222. _this._lastFrameTime = now;
  98223. // Stop the animation if there is user interaction and the animation should stop for this interaction
  98224. _this._applyUserInteraction();
  98225. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  98226. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  98227. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  98228. // Step camera rotation by rotation speed
  98229. if (_this._attachedCamera) {
  98230. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  98231. }
  98232. });
  98233. };
  98234. AutoRotationBehavior.prototype.detach = function () {
  98235. if (!this._attachedCamera) {
  98236. return;
  98237. }
  98238. var scene = this._attachedCamera.getScene();
  98239. if (this._onPrePointerObservableObserver) {
  98240. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  98241. }
  98242. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  98243. this._attachedCamera = null;
  98244. };
  98245. /**
  98246. * Returns true if user is scrolling.
  98247. * @return true if user is scrolling.
  98248. */
  98249. AutoRotationBehavior.prototype._userIsZooming = function () {
  98250. if (!this._attachedCamera) {
  98251. return false;
  98252. }
  98253. return this._attachedCamera.inertialRadiusOffset !== 0;
  98254. };
  98255. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  98256. if (!this._attachedCamera) {
  98257. return false;
  98258. }
  98259. var zoomHasHitLimit = false;
  98260. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  98261. zoomHasHitLimit = true;
  98262. }
  98263. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  98264. this._lastFrameRadius = this._attachedCamera.radius;
  98265. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  98266. };
  98267. /**
  98268. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  98269. */
  98270. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  98271. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  98272. this._lastInteractionTime = BABYLON.Tools.Now;
  98273. }
  98274. };
  98275. // Tools
  98276. AutoRotationBehavior.prototype._userIsMoving = function () {
  98277. if (!this._attachedCamera) {
  98278. return false;
  98279. }
  98280. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  98281. this._attachedCamera.inertialBetaOffset !== 0 ||
  98282. this._attachedCamera.inertialRadiusOffset !== 0 ||
  98283. this._attachedCamera.inertialPanningX !== 0 ||
  98284. this._attachedCamera.inertialPanningY !== 0 ||
  98285. this._isPointerDown;
  98286. };
  98287. return AutoRotationBehavior;
  98288. }());
  98289. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  98290. })(BABYLON || (BABYLON = {}));
  98291. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  98292. var BABYLON;
  98293. (function (BABYLON) {
  98294. var NullEngineOptions = /** @class */ (function () {
  98295. function NullEngineOptions() {
  98296. this.renderWidth = 512;
  98297. this.renderHeight = 256;
  98298. this.textureSize = 512;
  98299. this.deterministicLockstep = false;
  98300. this.lockstepMaxSteps = 4;
  98301. }
  98302. return NullEngineOptions;
  98303. }());
  98304. BABYLON.NullEngineOptions = NullEngineOptions;
  98305. /**
  98306. * The null engine class provides support for headless version of babylon.js.
  98307. * This can be used in server side scenario or for testing purposes
  98308. */
  98309. var NullEngine = /** @class */ (function (_super) {
  98310. __extends(NullEngine, _super);
  98311. function NullEngine(options) {
  98312. if (options === void 0) { options = new NullEngineOptions(); }
  98313. var _this = _super.call(this, null) || this;
  98314. if (options.deterministicLockstep === undefined) {
  98315. options.deterministicLockstep = false;
  98316. }
  98317. if (options.lockstepMaxSteps === undefined) {
  98318. options.lockstepMaxSteps = 4;
  98319. }
  98320. _this._options = options;
  98321. // Init caps
  98322. // We consider we are on a webgl1 capable device
  98323. _this._caps = new BABYLON.EngineCapabilities();
  98324. _this._caps.maxTexturesImageUnits = 16;
  98325. _this._caps.maxVertexTextureImageUnits = 16;
  98326. _this._caps.maxTextureSize = 512;
  98327. _this._caps.maxCubemapTextureSize = 512;
  98328. _this._caps.maxRenderTextureSize = 512;
  98329. _this._caps.maxVertexAttribs = 16;
  98330. _this._caps.maxVaryingVectors = 16;
  98331. _this._caps.maxFragmentUniformVectors = 16;
  98332. _this._caps.maxVertexUniformVectors = 16;
  98333. // Extensions
  98334. _this._caps.standardDerivatives = false;
  98335. _this._caps.astc = null;
  98336. _this._caps.s3tc = null;
  98337. _this._caps.pvrtc = null;
  98338. _this._caps.etc1 = null;
  98339. _this._caps.etc2 = null;
  98340. _this._caps.textureAnisotropicFilterExtension = null;
  98341. _this._caps.maxAnisotropy = 0;
  98342. _this._caps.uintIndices = false;
  98343. _this._caps.fragmentDepthSupported = false;
  98344. _this._caps.highPrecisionShaderSupported = true;
  98345. _this._caps.colorBufferFloat = false;
  98346. _this._caps.textureFloat = false;
  98347. _this._caps.textureFloatLinearFiltering = false;
  98348. _this._caps.textureFloatRender = false;
  98349. _this._caps.textureHalfFloat = false;
  98350. _this._caps.textureHalfFloatLinearFiltering = false;
  98351. _this._caps.textureHalfFloatRender = false;
  98352. _this._caps.textureLOD = false;
  98353. _this._caps.drawBuffersExtension = false;
  98354. _this._caps.depthTextureExtension = false;
  98355. _this._caps.vertexArrayObject = false;
  98356. _this._caps.instancedArrays = false;
  98357. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  98358. // Wrappers
  98359. if (typeof URL === "undefined") {
  98360. URL = {
  98361. createObjectURL: function () { },
  98362. revokeObjectURL: function () { }
  98363. };
  98364. }
  98365. if (typeof Blob === "undefined") {
  98366. Blob = function () { };
  98367. }
  98368. return _this;
  98369. }
  98370. NullEngine.prototype.isDeterministicLockStep = function () {
  98371. return this._options.deterministicLockstep;
  98372. };
  98373. NullEngine.prototype.getLockstepMaxSteps = function () {
  98374. return this._options.lockstepMaxSteps;
  98375. };
  98376. NullEngine.prototype.getHardwareScalingLevel = function () {
  98377. return 1.0;
  98378. };
  98379. NullEngine.prototype.createVertexBuffer = function (vertices) {
  98380. return {
  98381. capacity: 0,
  98382. references: 1,
  98383. is32Bits: false
  98384. };
  98385. };
  98386. NullEngine.prototype.createIndexBuffer = function (indices) {
  98387. return {
  98388. capacity: 0,
  98389. references: 1,
  98390. is32Bits: false
  98391. };
  98392. };
  98393. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  98394. if (stencil === void 0) { stencil = false; }
  98395. };
  98396. NullEngine.prototype.getRenderWidth = function (useScreen) {
  98397. if (useScreen === void 0) { useScreen = false; }
  98398. if (!useScreen && this._currentRenderTarget) {
  98399. return this._currentRenderTarget.width;
  98400. }
  98401. return this._options.renderWidth;
  98402. };
  98403. NullEngine.prototype.getRenderHeight = function (useScreen) {
  98404. if (useScreen === void 0) { useScreen = false; }
  98405. if (!useScreen && this._currentRenderTarget) {
  98406. return this._currentRenderTarget.height;
  98407. }
  98408. return this._options.renderHeight;
  98409. };
  98410. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  98411. this._cachedViewport = viewport;
  98412. };
  98413. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  98414. return {
  98415. transformFeedback: null,
  98416. __SPECTOR_rebuildProgram: null
  98417. };
  98418. };
  98419. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  98420. return [];
  98421. };
  98422. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  98423. return [];
  98424. };
  98425. NullEngine.prototype.bindSamplers = function (effect) {
  98426. this._currentEffect = null;
  98427. };
  98428. NullEngine.prototype.enableEffect = function (effect) {
  98429. this._currentEffect = effect;
  98430. if (effect.onBind) {
  98431. effect.onBind(effect);
  98432. }
  98433. effect.onBindObservable.notifyObservers(effect);
  98434. };
  98435. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  98436. if (zOffset === void 0) { zOffset = 0; }
  98437. if (reverseSide === void 0) { reverseSide = false; }
  98438. };
  98439. NullEngine.prototype.setIntArray = function (uniform, array) {
  98440. };
  98441. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  98442. };
  98443. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  98444. };
  98445. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  98446. };
  98447. NullEngine.prototype.setFloatArray = function (uniform, array) {
  98448. };
  98449. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  98450. };
  98451. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  98452. };
  98453. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  98454. };
  98455. NullEngine.prototype.setArray = function (uniform, array) {
  98456. };
  98457. NullEngine.prototype.setArray2 = function (uniform, array) {
  98458. };
  98459. NullEngine.prototype.setArray3 = function (uniform, array) {
  98460. };
  98461. NullEngine.prototype.setArray4 = function (uniform, array) {
  98462. };
  98463. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  98464. };
  98465. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  98466. };
  98467. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  98468. };
  98469. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  98470. };
  98471. NullEngine.prototype.setFloat = function (uniform, value) {
  98472. };
  98473. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  98474. };
  98475. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  98476. };
  98477. NullEngine.prototype.setBool = function (uniform, bool) {
  98478. };
  98479. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  98480. };
  98481. NullEngine.prototype.setColor3 = function (uniform, color3) {
  98482. };
  98483. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  98484. };
  98485. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  98486. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  98487. if (this._alphaMode === mode) {
  98488. return;
  98489. }
  98490. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  98491. if (!noDepthWriteChange) {
  98492. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  98493. }
  98494. this._alphaMode = mode;
  98495. };
  98496. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  98497. };
  98498. NullEngine.prototype.wipeCaches = function (bruteForce) {
  98499. if (this.preventCacheWipeBetweenFrames) {
  98500. return;
  98501. }
  98502. this.resetTextureCache();
  98503. this._currentEffect = null;
  98504. if (bruteForce) {
  98505. this._currentProgram = null;
  98506. this._stencilState.reset();
  98507. this._depthCullingState.reset();
  98508. this._alphaState.reset();
  98509. }
  98510. this._cachedVertexBuffers = null;
  98511. this._cachedIndexBuffer = null;
  98512. this._cachedEffectForVertexBuffers = null;
  98513. };
  98514. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  98515. };
  98516. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  98517. };
  98518. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  98519. };
  98520. NullEngine.prototype._createTexture = function () {
  98521. return {};
  98522. };
  98523. NullEngine.prototype._releaseTexture = function (texture) {
  98524. };
  98525. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  98526. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  98527. if (onLoad === void 0) { onLoad = null; }
  98528. if (onError === void 0) { onError = null; }
  98529. if (buffer === void 0) { buffer = null; }
  98530. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  98531. var url = String(urlArg);
  98532. texture.url = url;
  98533. texture.generateMipMaps = !noMipmap;
  98534. texture.samplingMode = samplingMode;
  98535. texture.invertY = invertY;
  98536. texture.baseWidth = this._options.textureSize;
  98537. texture.baseHeight = this._options.textureSize;
  98538. texture.width = this._options.textureSize;
  98539. texture.height = this._options.textureSize;
  98540. if (format) {
  98541. texture.format = format;
  98542. }
  98543. texture.isReady = true;
  98544. if (onLoad) {
  98545. onLoad();
  98546. }
  98547. this._internalTexturesCache.push(texture);
  98548. return texture;
  98549. };
  98550. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  98551. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  98552. if (options !== undefined && typeof options === "object") {
  98553. fullOptions.generateMipMaps = options.generateMipMaps;
  98554. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  98555. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  98556. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  98557. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  98558. }
  98559. else {
  98560. fullOptions.generateMipMaps = options;
  98561. fullOptions.generateDepthBuffer = true;
  98562. fullOptions.generateStencilBuffer = false;
  98563. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  98564. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  98565. }
  98566. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  98567. var width = size.width || size;
  98568. var height = size.height || size;
  98569. texture._depthStencilBuffer = {};
  98570. texture._framebuffer = {};
  98571. texture.baseWidth = width;
  98572. texture.baseHeight = height;
  98573. texture.width = width;
  98574. texture.height = height;
  98575. texture.isReady = true;
  98576. texture.samples = 1;
  98577. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  98578. texture.samplingMode = fullOptions.samplingMode;
  98579. texture.type = fullOptions.type;
  98580. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  98581. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  98582. this._internalTexturesCache.push(texture);
  98583. return texture;
  98584. };
  98585. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  98586. texture.samplingMode = samplingMode;
  98587. };
  98588. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  98589. if (this._currentRenderTarget) {
  98590. this.unBindFramebuffer(this._currentRenderTarget);
  98591. }
  98592. this._currentRenderTarget = texture;
  98593. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  98594. if (this._cachedViewport && !forceFullscreenViewport) {
  98595. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  98596. }
  98597. };
  98598. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  98599. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  98600. this._currentRenderTarget = null;
  98601. if (onBeforeUnbind) {
  98602. if (texture._MSAAFramebuffer) {
  98603. this._currentFramebuffer = texture._framebuffer;
  98604. }
  98605. onBeforeUnbind();
  98606. }
  98607. this._currentFramebuffer = null;
  98608. };
  98609. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  98610. var vbo = {
  98611. capacity: 1,
  98612. references: 1,
  98613. is32Bits: false
  98614. };
  98615. return vbo;
  98616. };
  98617. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  98618. if (offset === void 0) { offset = 0; }
  98619. };
  98620. /**
  98621. * Updates a dynamic vertex buffer.
  98622. * @param vertexBuffer the vertex buffer to update
  98623. * @param data the data used to update the vertex buffer
  98624. * @param byteOffset the byte offset of the data (optional)
  98625. * @param byteLength the byte length of the data (optional)
  98626. */
  98627. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  98628. };
  98629. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  98630. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  98631. this._boundTexturesCache[this._activeChannel] = texture;
  98632. return true;
  98633. }
  98634. return false;
  98635. };
  98636. NullEngine.prototype._bindTexture = function (channel, texture) {
  98637. if (channel < 0) {
  98638. return;
  98639. }
  98640. this._bindTextureDirectly(0, texture);
  98641. };
  98642. NullEngine.prototype._releaseBuffer = function (buffer) {
  98643. buffer.references--;
  98644. if (buffer.references === 0) {
  98645. return true;
  98646. }
  98647. return false;
  98648. };
  98649. NullEngine.prototype.releaseEffects = function () {
  98650. };
  98651. return NullEngine;
  98652. }(BABYLON.Engine));
  98653. BABYLON.NullEngine = NullEngine;
  98654. })(BABYLON || (BABYLON = {}));
  98655. //# sourceMappingURL=babylon.nullEngine.js.map
  98656. var BABYLON;
  98657. (function (BABYLON) {
  98658. /**
  98659. * This class can be used to get instrumentation data from a Babylon engine
  98660. */
  98661. var EngineInstrumentation = /** @class */ (function () {
  98662. function EngineInstrumentation(engine) {
  98663. this.engine = engine;
  98664. this._captureGPUFrameTime = false;
  98665. this._gpuFrameTime = new BABYLON.PerfCounter();
  98666. this._captureShaderCompilationTime = false;
  98667. this._shaderCompilationTime = new BABYLON.PerfCounter();
  98668. // Observers
  98669. this._onBeginFrameObserver = null;
  98670. this._onEndFrameObserver = null;
  98671. this._onBeforeShaderCompilationObserver = null;
  98672. this._onAfterShaderCompilationObserver = null;
  98673. }
  98674. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  98675. // Properties
  98676. /**
  98677. * Gets the perf counter used for GPU frame time
  98678. */
  98679. get: function () {
  98680. return this._gpuFrameTime;
  98681. },
  98682. enumerable: true,
  98683. configurable: true
  98684. });
  98685. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  98686. /**
  98687. * Gets the GPU frame time capture status
  98688. */
  98689. get: function () {
  98690. return this._captureGPUFrameTime;
  98691. },
  98692. /**
  98693. * Enable or disable the GPU frame time capture
  98694. */
  98695. set: function (value) {
  98696. var _this = this;
  98697. if (value === this._captureGPUFrameTime) {
  98698. return;
  98699. }
  98700. this._captureGPUFrameTime = value;
  98701. if (value) {
  98702. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  98703. if (!_this._gpuFrameTimeToken) {
  98704. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  98705. }
  98706. });
  98707. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  98708. if (!_this._gpuFrameTimeToken) {
  98709. return;
  98710. }
  98711. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  98712. if (time > -1) {
  98713. _this._gpuFrameTimeToken = null;
  98714. _this._gpuFrameTime.fetchNewFrame();
  98715. _this._gpuFrameTime.addCount(time, true);
  98716. }
  98717. });
  98718. }
  98719. else {
  98720. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  98721. this._onBeginFrameObserver = null;
  98722. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  98723. this._onEndFrameObserver = null;
  98724. }
  98725. },
  98726. enumerable: true,
  98727. configurable: true
  98728. });
  98729. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  98730. /**
  98731. * Gets the perf counter used for shader compilation time
  98732. */
  98733. get: function () {
  98734. return this._shaderCompilationTime;
  98735. },
  98736. enumerable: true,
  98737. configurable: true
  98738. });
  98739. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  98740. /**
  98741. * Gets the shader compilation time capture status
  98742. */
  98743. get: function () {
  98744. return this._captureShaderCompilationTime;
  98745. },
  98746. /**
  98747. * Enable or disable the shader compilation time capture
  98748. */
  98749. set: function (value) {
  98750. var _this = this;
  98751. if (value === this._captureShaderCompilationTime) {
  98752. return;
  98753. }
  98754. this._captureShaderCompilationTime = value;
  98755. if (value) {
  98756. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  98757. _this._shaderCompilationTime.fetchNewFrame();
  98758. _this._shaderCompilationTime.beginMonitoring();
  98759. });
  98760. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  98761. _this._shaderCompilationTime.endMonitoring();
  98762. });
  98763. }
  98764. else {
  98765. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  98766. this._onBeforeShaderCompilationObserver = null;
  98767. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  98768. this._onAfterShaderCompilationObserver = null;
  98769. }
  98770. },
  98771. enumerable: true,
  98772. configurable: true
  98773. });
  98774. EngineInstrumentation.prototype.dispose = function () {
  98775. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  98776. this._onBeginFrameObserver = null;
  98777. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  98778. this._onEndFrameObserver = null;
  98779. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  98780. this._onBeforeShaderCompilationObserver = null;
  98781. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  98782. this._onAfterShaderCompilationObserver = null;
  98783. this.engine = null;
  98784. };
  98785. return EngineInstrumentation;
  98786. }());
  98787. BABYLON.EngineInstrumentation = EngineInstrumentation;
  98788. })(BABYLON || (BABYLON = {}));
  98789. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  98790. var BABYLON;
  98791. (function (BABYLON) {
  98792. /**
  98793. * This class can be used to get instrumentation data from a Babylon engine
  98794. */
  98795. var SceneInstrumentation = /** @class */ (function () {
  98796. function SceneInstrumentation(scene) {
  98797. var _this = this;
  98798. this.scene = scene;
  98799. this._captureActiveMeshesEvaluationTime = false;
  98800. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  98801. this._captureRenderTargetsRenderTime = false;
  98802. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  98803. this._captureFrameTime = false;
  98804. this._frameTime = new BABYLON.PerfCounter();
  98805. this._captureRenderTime = false;
  98806. this._renderTime = new BABYLON.PerfCounter();
  98807. this._captureInterFrameTime = false;
  98808. this._interFrameTime = new BABYLON.PerfCounter();
  98809. this._captureParticlesRenderTime = false;
  98810. this._particlesRenderTime = new BABYLON.PerfCounter();
  98811. this._captureSpritesRenderTime = false;
  98812. this._spritesRenderTime = new BABYLON.PerfCounter();
  98813. this._capturePhysicsTime = false;
  98814. this._physicsTime = new BABYLON.PerfCounter();
  98815. this._captureAnimationsTime = false;
  98816. this._animationsTime = new BABYLON.PerfCounter();
  98817. this._captureCameraRenderTime = false;
  98818. this._cameraRenderTime = new BABYLON.PerfCounter();
  98819. // Observers
  98820. this._onBeforeActiveMeshesEvaluationObserver = null;
  98821. this._onAfterActiveMeshesEvaluationObserver = null;
  98822. this._onBeforeRenderTargetsRenderObserver = null;
  98823. this._onAfterRenderTargetsRenderObserver = null;
  98824. this._onAfterRenderObserver = null;
  98825. this._onBeforeDrawPhaseObserver = null;
  98826. this._onAfterDrawPhaseObserver = null;
  98827. this._onBeforeAnimationsObserver = null;
  98828. this._onBeforeParticlesRenderingObserver = null;
  98829. this._onAfterParticlesRenderingObserver = null;
  98830. this._onBeforeSpritesRenderingObserver = null;
  98831. this._onAfterSpritesRenderingObserver = null;
  98832. this._onBeforePhysicsObserver = null;
  98833. this._onAfterPhysicsObserver = null;
  98834. this._onAfterAnimationsObserver = null;
  98835. this._onBeforeCameraRenderObserver = null;
  98836. this._onAfterCameraRenderObserver = null;
  98837. // Before render
  98838. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  98839. if (_this._captureActiveMeshesEvaluationTime) {
  98840. _this._activeMeshesEvaluationTime.fetchNewFrame();
  98841. }
  98842. if (_this._captureRenderTargetsRenderTime) {
  98843. _this._renderTargetsRenderTime.fetchNewFrame();
  98844. }
  98845. if (_this._captureFrameTime) {
  98846. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  98847. _this._frameTime.beginMonitoring();
  98848. }
  98849. if (_this._captureInterFrameTime) {
  98850. _this._interFrameTime.endMonitoring();
  98851. }
  98852. if (_this._captureParticlesRenderTime) {
  98853. _this._particlesRenderTime.fetchNewFrame();
  98854. }
  98855. if (_this._captureSpritesRenderTime) {
  98856. _this._spritesRenderTime.fetchNewFrame();
  98857. }
  98858. if (_this._captureAnimationsTime) {
  98859. _this._animationsTime.beginMonitoring();
  98860. }
  98861. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  98862. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  98863. });
  98864. // After render
  98865. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  98866. if (_this._captureFrameTime) {
  98867. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  98868. _this._frameTime.endMonitoring();
  98869. }
  98870. if (_this._captureRenderTime) {
  98871. _this._renderTime.endMonitoring(false);
  98872. }
  98873. if (_this._captureInterFrameTime) {
  98874. _this._interFrameTime.beginMonitoring();
  98875. }
  98876. });
  98877. }
  98878. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  98879. // Properties
  98880. /**
  98881. * Gets the perf counter used for active meshes evaluation time
  98882. */
  98883. get: function () {
  98884. return this._activeMeshesEvaluationTime;
  98885. },
  98886. enumerable: true,
  98887. configurable: true
  98888. });
  98889. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  98890. /**
  98891. * Gets the active meshes evaluation time capture status
  98892. */
  98893. get: function () {
  98894. return this._captureActiveMeshesEvaluationTime;
  98895. },
  98896. /**
  98897. * Enable or disable the active meshes evaluation time capture
  98898. */
  98899. set: function (value) {
  98900. var _this = this;
  98901. if (value === this._captureActiveMeshesEvaluationTime) {
  98902. return;
  98903. }
  98904. this._captureActiveMeshesEvaluationTime = value;
  98905. if (value) {
  98906. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  98907. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  98908. _this._activeMeshesEvaluationTime.beginMonitoring();
  98909. });
  98910. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  98911. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  98912. _this._activeMeshesEvaluationTime.endMonitoring();
  98913. });
  98914. }
  98915. else {
  98916. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  98917. this._onBeforeActiveMeshesEvaluationObserver = null;
  98918. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  98919. this._onAfterActiveMeshesEvaluationObserver = null;
  98920. }
  98921. },
  98922. enumerable: true,
  98923. configurable: true
  98924. });
  98925. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  98926. /**
  98927. * Gets the perf counter used for render targets render time
  98928. */
  98929. get: function () {
  98930. return this._renderTargetsRenderTime;
  98931. },
  98932. enumerable: true,
  98933. configurable: true
  98934. });
  98935. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  98936. /**
  98937. * Gets the render targets render time capture status
  98938. */
  98939. get: function () {
  98940. return this._captureRenderTargetsRenderTime;
  98941. },
  98942. /**
  98943. * Enable or disable the render targets render time capture
  98944. */
  98945. set: function (value) {
  98946. var _this = this;
  98947. if (value === this._captureRenderTargetsRenderTime) {
  98948. return;
  98949. }
  98950. this._captureRenderTargetsRenderTime = value;
  98951. if (value) {
  98952. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  98953. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  98954. _this._renderTargetsRenderTime.beginMonitoring();
  98955. });
  98956. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  98957. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  98958. _this._renderTargetsRenderTime.endMonitoring(false);
  98959. });
  98960. }
  98961. else {
  98962. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  98963. this._onBeforeRenderTargetsRenderObserver = null;
  98964. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  98965. this._onAfterRenderTargetsRenderObserver = null;
  98966. }
  98967. },
  98968. enumerable: true,
  98969. configurable: true
  98970. });
  98971. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  98972. /**
  98973. * Gets the perf counter used for particles render time
  98974. */
  98975. get: function () {
  98976. return this._particlesRenderTime;
  98977. },
  98978. enumerable: true,
  98979. configurable: true
  98980. });
  98981. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  98982. /**
  98983. * Gets the particles render time capture status
  98984. */
  98985. get: function () {
  98986. return this._captureParticlesRenderTime;
  98987. },
  98988. /**
  98989. * Enable or disable the particles render time capture
  98990. */
  98991. set: function (value) {
  98992. var _this = this;
  98993. if (value === this._captureParticlesRenderTime) {
  98994. return;
  98995. }
  98996. this._captureParticlesRenderTime = value;
  98997. if (value) {
  98998. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  98999. BABYLON.Tools.StartPerformanceCounter("Particles");
  99000. _this._particlesRenderTime.beginMonitoring();
  99001. });
  99002. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  99003. BABYLON.Tools.EndPerformanceCounter("Particles");
  99004. _this._particlesRenderTime.endMonitoring(false);
  99005. });
  99006. }
  99007. else {
  99008. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  99009. this._onBeforeParticlesRenderingObserver = null;
  99010. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  99011. this._onAfterParticlesRenderingObserver = null;
  99012. }
  99013. },
  99014. enumerable: true,
  99015. configurable: true
  99016. });
  99017. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  99018. /**
  99019. * Gets the perf counter used for sprites render time
  99020. */
  99021. get: function () {
  99022. return this._spritesRenderTime;
  99023. },
  99024. enumerable: true,
  99025. configurable: true
  99026. });
  99027. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  99028. /**
  99029. * Gets the sprites render time capture status
  99030. */
  99031. get: function () {
  99032. return this._captureSpritesRenderTime;
  99033. },
  99034. /**
  99035. * Enable or disable the sprites render time capture
  99036. */
  99037. set: function (value) {
  99038. var _this = this;
  99039. if (value === this._captureSpritesRenderTime) {
  99040. return;
  99041. }
  99042. this._captureSpritesRenderTime = value;
  99043. if (value) {
  99044. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  99045. BABYLON.Tools.StartPerformanceCounter("Sprites");
  99046. _this._spritesRenderTime.beginMonitoring();
  99047. });
  99048. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  99049. BABYLON.Tools.EndPerformanceCounter("Sprites");
  99050. _this._spritesRenderTime.endMonitoring(false);
  99051. });
  99052. }
  99053. else {
  99054. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  99055. this._onBeforeSpritesRenderingObserver = null;
  99056. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  99057. this._onAfterSpritesRenderingObserver = null;
  99058. }
  99059. },
  99060. enumerable: true,
  99061. configurable: true
  99062. });
  99063. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  99064. /**
  99065. * Gets the perf counter used for physics time
  99066. */
  99067. get: function () {
  99068. return this._physicsTime;
  99069. },
  99070. enumerable: true,
  99071. configurable: true
  99072. });
  99073. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  99074. /**
  99075. * Gets the physics time capture status
  99076. */
  99077. get: function () {
  99078. return this._capturePhysicsTime;
  99079. },
  99080. /**
  99081. * Enable or disable the physics time capture
  99082. */
  99083. set: function (value) {
  99084. var _this = this;
  99085. if (value === this._capturePhysicsTime) {
  99086. return;
  99087. }
  99088. this._capturePhysicsTime = value;
  99089. if (value) {
  99090. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  99091. BABYLON.Tools.StartPerformanceCounter("Physics");
  99092. _this._physicsTime.beginMonitoring();
  99093. });
  99094. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  99095. BABYLON.Tools.EndPerformanceCounter("Physics");
  99096. _this._physicsTime.endMonitoring();
  99097. });
  99098. }
  99099. else {
  99100. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  99101. this._onBeforePhysicsObserver = null;
  99102. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  99103. this._onAfterPhysicsObserver = null;
  99104. }
  99105. },
  99106. enumerable: true,
  99107. configurable: true
  99108. });
  99109. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  99110. /**
  99111. * Gets the perf counter used for animations time
  99112. */
  99113. get: function () {
  99114. return this._animationsTime;
  99115. },
  99116. enumerable: true,
  99117. configurable: true
  99118. });
  99119. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  99120. /**
  99121. * Gets the animations time capture status
  99122. */
  99123. get: function () {
  99124. return this._captureAnimationsTime;
  99125. },
  99126. /**
  99127. * Enable or disable the animations time capture
  99128. */
  99129. set: function (value) {
  99130. var _this = this;
  99131. if (value === this._captureAnimationsTime) {
  99132. return;
  99133. }
  99134. this._captureAnimationsTime = value;
  99135. if (value) {
  99136. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  99137. _this._animationsTime.endMonitoring();
  99138. });
  99139. }
  99140. else {
  99141. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  99142. this._onAfterAnimationsObserver = null;
  99143. }
  99144. },
  99145. enumerable: true,
  99146. configurable: true
  99147. });
  99148. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  99149. /**
  99150. * Gets the perf counter used for frame time capture
  99151. */
  99152. get: function () {
  99153. return this._frameTime;
  99154. },
  99155. enumerable: true,
  99156. configurable: true
  99157. });
  99158. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  99159. /**
  99160. * Gets the frame time capture status
  99161. */
  99162. get: function () {
  99163. return this._captureFrameTime;
  99164. },
  99165. /**
  99166. * Enable or disable the frame time capture
  99167. */
  99168. set: function (value) {
  99169. this._captureFrameTime = value;
  99170. },
  99171. enumerable: true,
  99172. configurable: true
  99173. });
  99174. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  99175. /**
  99176. * Gets the perf counter used for inter-frames time capture
  99177. */
  99178. get: function () {
  99179. return this._interFrameTime;
  99180. },
  99181. enumerable: true,
  99182. configurable: true
  99183. });
  99184. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  99185. /**
  99186. * Gets the inter-frames time capture status
  99187. */
  99188. get: function () {
  99189. return this._captureInterFrameTime;
  99190. },
  99191. /**
  99192. * Enable or disable the inter-frames time capture
  99193. */
  99194. set: function (value) {
  99195. this._captureInterFrameTime = value;
  99196. },
  99197. enumerable: true,
  99198. configurable: true
  99199. });
  99200. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  99201. /**
  99202. * Gets the perf counter used for render time capture
  99203. */
  99204. get: function () {
  99205. return this._renderTime;
  99206. },
  99207. enumerable: true,
  99208. configurable: true
  99209. });
  99210. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  99211. /**
  99212. * Gets the render time capture status
  99213. */
  99214. get: function () {
  99215. return this._captureRenderTime;
  99216. },
  99217. /**
  99218. * Enable or disable the render time capture
  99219. */
  99220. set: function (value) {
  99221. var _this = this;
  99222. if (value === this._captureRenderTime) {
  99223. return;
  99224. }
  99225. this._captureRenderTime = value;
  99226. if (value) {
  99227. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  99228. _this._renderTime.beginMonitoring();
  99229. BABYLON.Tools.StartPerformanceCounter("Main render");
  99230. });
  99231. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  99232. _this._renderTime.endMonitoring(false);
  99233. BABYLON.Tools.EndPerformanceCounter("Main render");
  99234. });
  99235. }
  99236. else {
  99237. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  99238. this._onBeforeDrawPhaseObserver = null;
  99239. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  99240. this._onAfterDrawPhaseObserver = null;
  99241. }
  99242. },
  99243. enumerable: true,
  99244. configurable: true
  99245. });
  99246. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  99247. /**
  99248. * Gets the perf counter used for camera render time capture
  99249. */
  99250. get: function () {
  99251. return this._cameraRenderTime;
  99252. },
  99253. enumerable: true,
  99254. configurable: true
  99255. });
  99256. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  99257. /**
  99258. * Gets the camera render time capture status
  99259. */
  99260. get: function () {
  99261. return this._captureCameraRenderTime;
  99262. },
  99263. /**
  99264. * Enable or disable the camera render time capture
  99265. */
  99266. set: function (value) {
  99267. var _this = this;
  99268. if (value === this._captureCameraRenderTime) {
  99269. return;
  99270. }
  99271. this._captureCameraRenderTime = value;
  99272. if (value) {
  99273. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  99274. _this._cameraRenderTime.beginMonitoring();
  99275. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  99276. });
  99277. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  99278. _this._cameraRenderTime.endMonitoring(false);
  99279. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  99280. });
  99281. }
  99282. else {
  99283. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  99284. this._onBeforeCameraRenderObserver = null;
  99285. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  99286. this._onAfterCameraRenderObserver = null;
  99287. }
  99288. },
  99289. enumerable: true,
  99290. configurable: true
  99291. });
  99292. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  99293. /**
  99294. * Gets the perf counter used for draw calls
  99295. */
  99296. get: function () {
  99297. return this.scene.getEngine()._drawCalls;
  99298. },
  99299. enumerable: true,
  99300. configurable: true
  99301. });
  99302. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  99303. /**
  99304. * Gets the perf counter used for texture collisions
  99305. */
  99306. get: function () {
  99307. return this.scene.getEngine()._textureCollisions;
  99308. },
  99309. enumerable: true,
  99310. configurable: true
  99311. });
  99312. SceneInstrumentation.prototype.dispose = function () {
  99313. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  99314. this._onAfterRenderObserver = null;
  99315. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  99316. this._onBeforeActiveMeshesEvaluationObserver = null;
  99317. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  99318. this._onAfterActiveMeshesEvaluationObserver = null;
  99319. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  99320. this._onBeforeRenderTargetsRenderObserver = null;
  99321. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  99322. this._onAfterRenderTargetsRenderObserver = null;
  99323. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  99324. this._onBeforeAnimationsObserver = null;
  99325. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  99326. this._onBeforeParticlesRenderingObserver = null;
  99327. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  99328. this._onAfterParticlesRenderingObserver = null;
  99329. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  99330. this._onBeforeSpritesRenderingObserver = null;
  99331. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  99332. this._onAfterSpritesRenderingObserver = null;
  99333. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  99334. this._onBeforeDrawPhaseObserver = null;
  99335. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  99336. this._onAfterDrawPhaseObserver = null;
  99337. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  99338. this._onBeforePhysicsObserver = null;
  99339. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  99340. this._onAfterPhysicsObserver = null;
  99341. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  99342. this._onAfterAnimationsObserver = null;
  99343. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  99344. this._onBeforeCameraRenderObserver = null;
  99345. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  99346. this._onAfterCameraRenderObserver = null;
  99347. this.scene = null;
  99348. };
  99349. return SceneInstrumentation;
  99350. }());
  99351. BABYLON.SceneInstrumentation = SceneInstrumentation;
  99352. })(BABYLON || (BABYLON = {}));
  99353. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  99354. var BABYLON;
  99355. (function (BABYLON) {
  99356. /**
  99357. * @hidden
  99358. **/
  99359. var _TimeToken = /** @class */ (function () {
  99360. function _TimeToken() {
  99361. this._timeElapsedQueryEnded = false;
  99362. }
  99363. return _TimeToken;
  99364. }());
  99365. BABYLON._TimeToken = _TimeToken;
  99366. })(BABYLON || (BABYLON = {}));
  99367. //# sourceMappingURL=babylon.timeToken.js.map
  99368. var BABYLON;
  99369. (function (BABYLON) {
  99370. /**
  99371. * Background material defines definition.
  99372. * @hidden Mainly internal Use
  99373. */
  99374. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  99375. __extends(BackgroundMaterialDefines, _super);
  99376. /**
  99377. * Constructor of the defines.
  99378. */
  99379. function BackgroundMaterialDefines() {
  99380. var _this = _super.call(this) || this;
  99381. /**
  99382. * True if the diffuse texture is in use.
  99383. */
  99384. _this.DIFFUSE = false;
  99385. /**
  99386. * The direct UV channel to use.
  99387. */
  99388. _this.DIFFUSEDIRECTUV = 0;
  99389. /**
  99390. * True if the diffuse texture is in gamma space.
  99391. */
  99392. _this.GAMMADIFFUSE = false;
  99393. /**
  99394. * True if the diffuse texture has opacity in the alpha channel.
  99395. */
  99396. _this.DIFFUSEHASALPHA = false;
  99397. /**
  99398. * True if you want the material to fade to transparent at grazing angle.
  99399. */
  99400. _this.OPACITYFRESNEL = false;
  99401. /**
  99402. * True if an extra blur needs to be added in the reflection.
  99403. */
  99404. _this.REFLECTIONBLUR = false;
  99405. /**
  99406. * True if you want the material to fade to reflection at grazing angle.
  99407. */
  99408. _this.REFLECTIONFRESNEL = false;
  99409. /**
  99410. * True if you want the material to falloff as far as you move away from the scene center.
  99411. */
  99412. _this.REFLECTIONFALLOFF = false;
  99413. /**
  99414. * False if the current Webgl implementation does not support the texture lod extension.
  99415. */
  99416. _this.TEXTURELODSUPPORT = false;
  99417. /**
  99418. * True to ensure the data are premultiplied.
  99419. */
  99420. _this.PREMULTIPLYALPHA = false;
  99421. /**
  99422. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  99423. */
  99424. _this.USERGBCOLOR = false;
  99425. /**
  99426. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  99427. * stays aligned with the desired configuration.
  99428. */
  99429. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  99430. /**
  99431. * True to add noise in order to reduce the banding effect.
  99432. */
  99433. _this.NOISE = false;
  99434. /**
  99435. * is the reflection texture in BGR color scheme?
  99436. * Mainly used to solve a bug in ios10 video tag
  99437. */
  99438. _this.REFLECTIONBGR = false;
  99439. _this.IMAGEPROCESSING = false;
  99440. _this.VIGNETTE = false;
  99441. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  99442. _this.VIGNETTEBLENDMODEOPAQUE = false;
  99443. _this.TONEMAPPING = false;
  99444. _this.CONTRAST = false;
  99445. _this.COLORCURVES = false;
  99446. _this.COLORGRADING = false;
  99447. _this.COLORGRADING3D = false;
  99448. _this.SAMPLER3DGREENDEPTH = false;
  99449. _this.SAMPLER3DBGRMAP = false;
  99450. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  99451. _this.EXPOSURE = false;
  99452. // Reflection.
  99453. _this.REFLECTION = false;
  99454. _this.REFLECTIONMAP_3D = false;
  99455. _this.REFLECTIONMAP_SPHERICAL = false;
  99456. _this.REFLECTIONMAP_PLANAR = false;
  99457. _this.REFLECTIONMAP_CUBIC = false;
  99458. _this.REFLECTIONMAP_PROJECTION = false;
  99459. _this.REFLECTIONMAP_SKYBOX = false;
  99460. _this.REFLECTIONMAP_EXPLICIT = false;
  99461. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  99462. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  99463. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  99464. _this.INVERTCUBICMAP = false;
  99465. _this.REFLECTIONMAP_OPPOSITEZ = false;
  99466. _this.LODINREFLECTIONALPHA = false;
  99467. _this.GAMMAREFLECTION = false;
  99468. _this.RGBDREFLECTION = false;
  99469. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  99470. // Default BJS.
  99471. _this.MAINUV1 = false;
  99472. _this.MAINUV2 = false;
  99473. _this.UV1 = false;
  99474. _this.UV2 = false;
  99475. _this.CLIPPLANE = false;
  99476. _this.POINTSIZE = false;
  99477. _this.FOG = false;
  99478. _this.NORMAL = false;
  99479. _this.NUM_BONE_INFLUENCERS = 0;
  99480. _this.BonesPerMesh = 0;
  99481. _this.INSTANCES = false;
  99482. _this.SHADOWFLOAT = false;
  99483. _this.rebuild();
  99484. return _this;
  99485. }
  99486. return BackgroundMaterialDefines;
  99487. }(BABYLON.MaterialDefines));
  99488. /**
  99489. * Background material used to create an efficient environement around your scene.
  99490. */
  99491. var BackgroundMaterial = /** @class */ (function (_super) {
  99492. __extends(BackgroundMaterial, _super);
  99493. /**
  99494. * Instantiates a Background Material in the given scene
  99495. * @param name The friendly name of the material
  99496. * @param scene The scene to add the material to
  99497. */
  99498. function BackgroundMaterial(name, scene) {
  99499. var _this = _super.call(this, name, scene) || this;
  99500. /**
  99501. * Key light Color (multiply against the environement texture)
  99502. */
  99503. _this.primaryColor = BABYLON.Color3.White();
  99504. _this._primaryColorShadowLevel = 0;
  99505. _this._primaryColorHighlightLevel = 0;
  99506. /**
  99507. * Reflection Texture used in the material.
  99508. * Should be author in a specific way for the best result (refer to the documentation).
  99509. */
  99510. _this.reflectionTexture = null;
  99511. /**
  99512. * Reflection Texture level of blur.
  99513. *
  99514. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  99515. * texture twice.
  99516. */
  99517. _this.reflectionBlur = 0;
  99518. /**
  99519. * Diffuse Texture used in the material.
  99520. * Should be author in a specific way for the best result (refer to the documentation).
  99521. */
  99522. _this.diffuseTexture = null;
  99523. _this._shadowLights = null;
  99524. /**
  99525. * Specify the list of lights casting shadow on the material.
  99526. * All scene shadow lights will be included if null.
  99527. */
  99528. _this.shadowLights = null;
  99529. /**
  99530. * Helps adjusting the shadow to a softer level if required.
  99531. * 0 means black shadows and 1 means no shadows.
  99532. */
  99533. _this.shadowLevel = 0;
  99534. /**
  99535. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  99536. * It is usually zero but might be interesting to modify according to your setup.
  99537. */
  99538. _this.sceneCenter = BABYLON.Vector3.Zero();
  99539. /**
  99540. * This helps specifying that the material is falling off to the sky box at grazing angle.
  99541. * This helps ensuring a nice transition when the camera goes under the ground.
  99542. */
  99543. _this.opacityFresnel = true;
  99544. /**
  99545. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  99546. * This helps adding a mirror texture on the ground.
  99547. */
  99548. _this.reflectionFresnel = false;
  99549. /**
  99550. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  99551. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  99552. */
  99553. _this.reflectionFalloffDistance = 0.0;
  99554. /**
  99555. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  99556. */
  99557. _this.reflectionAmount = 1.0;
  99558. /**
  99559. * This specifies the weight of the reflection at grazing angle.
  99560. */
  99561. _this.reflectionReflectance0 = 0.05;
  99562. /**
  99563. * This specifies the weight of the reflection at a perpendicular point of view.
  99564. */
  99565. _this.reflectionReflectance90 = 0.5;
  99566. /**
  99567. * Helps to directly use the maps channels instead of their level.
  99568. */
  99569. _this.useRGBColor = true;
  99570. /**
  99571. * This helps reducing the banding effect that could occur on the background.
  99572. */
  99573. _this.enableNoise = false;
  99574. _this._fovMultiplier = 1.0;
  99575. /**
  99576. * Enable the FOV adjustment feature controlled by fovMultiplier.
  99577. */
  99578. _this.useEquirectangularFOV = false;
  99579. _this._maxSimultaneousLights = 4;
  99580. /**
  99581. * Number of Simultaneous lights allowed on the material.
  99582. */
  99583. _this.maxSimultaneousLights = 4;
  99584. /**
  99585. * Keep track of the image processing observer to allow dispose and replace.
  99586. */
  99587. _this._imageProcessingObserver = null;
  99588. /**
  99589. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  99590. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  99591. */
  99592. _this.switchToBGR = false;
  99593. // Temp values kept as cache in the material.
  99594. _this._renderTargets = new BABYLON.SmartArray(16);
  99595. _this._reflectionControls = BABYLON.Vector4.Zero();
  99596. _this._white = BABYLON.Color3.White();
  99597. _this._primaryShadowColor = BABYLON.Color3.Black();
  99598. _this._primaryHighlightColor = BABYLON.Color3.Black();
  99599. // Setup the default processing configuration to the scene.
  99600. _this._attachImageProcessingConfiguration(null);
  99601. _this.getRenderTargetTextures = function () {
  99602. _this._renderTargets.reset();
  99603. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  99604. _this._renderTargets.push(_this._diffuseTexture);
  99605. }
  99606. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  99607. _this._renderTargets.push(_this._reflectionTexture);
  99608. }
  99609. return _this._renderTargets;
  99610. };
  99611. return _this;
  99612. }
  99613. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  99614. /**
  99615. * Experimental Internal Use Only.
  99616. *
  99617. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  99618. * This acts as a helper to set the primary color to a more "human friendly" value.
  99619. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  99620. * output color as close as possible from the chosen value.
  99621. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  99622. * part of lighting setup.)
  99623. */
  99624. get: function () {
  99625. return this.__perceptualColor;
  99626. },
  99627. set: function (value) {
  99628. this.__perceptualColor = value;
  99629. this._computePrimaryColorFromPerceptualColor();
  99630. this._markAllSubMeshesAsLightsDirty();
  99631. },
  99632. enumerable: true,
  99633. configurable: true
  99634. });
  99635. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  99636. /**
  99637. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  99638. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  99639. */
  99640. get: function () {
  99641. return this._primaryColorShadowLevel;
  99642. },
  99643. set: function (value) {
  99644. this._primaryColorShadowLevel = value;
  99645. this._computePrimaryColors();
  99646. this._markAllSubMeshesAsLightsDirty();
  99647. },
  99648. enumerable: true,
  99649. configurable: true
  99650. });
  99651. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  99652. /**
  99653. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  99654. * The primary color is used at the level chosen to define what the white area would look.
  99655. */
  99656. get: function () {
  99657. return this._primaryColorHighlightLevel;
  99658. },
  99659. set: function (value) {
  99660. this._primaryColorHighlightLevel = value;
  99661. this._computePrimaryColors();
  99662. this._markAllSubMeshesAsLightsDirty();
  99663. },
  99664. enumerable: true,
  99665. configurable: true
  99666. });
  99667. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  99668. /**
  99669. * Sets the reflection reflectance fresnel values according to the default standard
  99670. * empirically know to work well :-)
  99671. */
  99672. set: function (value) {
  99673. var reflectionWeight = value;
  99674. if (reflectionWeight < 0.5) {
  99675. reflectionWeight = reflectionWeight * 2.0;
  99676. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  99677. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  99678. }
  99679. else {
  99680. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  99681. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  99682. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  99683. }
  99684. },
  99685. enumerable: true,
  99686. configurable: true
  99687. });
  99688. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  99689. /**
  99690. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  99691. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  99692. * Recommended to be keep at 1.0 except for special cases.
  99693. */
  99694. get: function () {
  99695. return this._fovMultiplier;
  99696. },
  99697. set: function (value) {
  99698. if (isNaN(value)) {
  99699. value = 1.0;
  99700. }
  99701. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  99702. },
  99703. enumerable: true,
  99704. configurable: true
  99705. });
  99706. /**
  99707. * Attaches a new image processing configuration to the PBR Material.
  99708. * @param configuration (if null the scene configuration will be use)
  99709. */
  99710. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  99711. var _this = this;
  99712. if (configuration === this._imageProcessingConfiguration) {
  99713. return;
  99714. }
  99715. // Detaches observer.
  99716. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  99717. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  99718. }
  99719. // Pick the scene configuration if needed.
  99720. if (!configuration) {
  99721. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  99722. }
  99723. else {
  99724. this._imageProcessingConfiguration = configuration;
  99725. }
  99726. // Attaches observer.
  99727. if (this._imageProcessingConfiguration) {
  99728. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  99729. _this._computePrimaryColorFromPerceptualColor();
  99730. _this._markAllSubMeshesAsImageProcessingDirty();
  99731. });
  99732. }
  99733. };
  99734. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  99735. /**
  99736. * Gets the image processing configuration used either in this material.
  99737. */
  99738. get: function () {
  99739. return this._imageProcessingConfiguration;
  99740. },
  99741. /**
  99742. * Sets the Default image processing configuration used either in the this material.
  99743. *
  99744. * If sets to null, the scene one is in use.
  99745. */
  99746. set: function (value) {
  99747. this._attachImageProcessingConfiguration(value);
  99748. // Ensure the effect will be rebuilt.
  99749. this._markAllSubMeshesAsTexturesDirty();
  99750. },
  99751. enumerable: true,
  99752. configurable: true
  99753. });
  99754. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  99755. /**
  99756. * Gets wether the color curves effect is enabled.
  99757. */
  99758. get: function () {
  99759. return this.imageProcessingConfiguration.colorCurvesEnabled;
  99760. },
  99761. /**
  99762. * Sets wether the color curves effect is enabled.
  99763. */
  99764. set: function (value) {
  99765. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  99766. },
  99767. enumerable: true,
  99768. configurable: true
  99769. });
  99770. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  99771. /**
  99772. * Gets wether the color grading effect is enabled.
  99773. */
  99774. get: function () {
  99775. return this.imageProcessingConfiguration.colorGradingEnabled;
  99776. },
  99777. /**
  99778. * Gets wether the color grading effect is enabled.
  99779. */
  99780. set: function (value) {
  99781. this.imageProcessingConfiguration.colorGradingEnabled = value;
  99782. },
  99783. enumerable: true,
  99784. configurable: true
  99785. });
  99786. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  99787. /**
  99788. * Gets wether tonemapping is enabled or not.
  99789. */
  99790. get: function () {
  99791. return this._imageProcessingConfiguration.toneMappingEnabled;
  99792. },
  99793. /**
  99794. * Sets wether tonemapping is enabled or not
  99795. */
  99796. set: function (value) {
  99797. this._imageProcessingConfiguration.toneMappingEnabled = value;
  99798. },
  99799. enumerable: true,
  99800. configurable: true
  99801. });
  99802. ;
  99803. ;
  99804. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  99805. /**
  99806. * The camera exposure used on this material.
  99807. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  99808. * This corresponds to a photographic exposure.
  99809. */
  99810. get: function () {
  99811. return this._imageProcessingConfiguration.exposure;
  99812. },
  99813. /**
  99814. * The camera exposure used on this material.
  99815. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  99816. * This corresponds to a photographic exposure.
  99817. */
  99818. set: function (value) {
  99819. this._imageProcessingConfiguration.exposure = value;
  99820. },
  99821. enumerable: true,
  99822. configurable: true
  99823. });
  99824. ;
  99825. ;
  99826. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  99827. /**
  99828. * Gets The camera contrast used on this material.
  99829. */
  99830. get: function () {
  99831. return this._imageProcessingConfiguration.contrast;
  99832. },
  99833. /**
  99834. * Sets The camera contrast used on this material.
  99835. */
  99836. set: function (value) {
  99837. this._imageProcessingConfiguration.contrast = value;
  99838. },
  99839. enumerable: true,
  99840. configurable: true
  99841. });
  99842. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  99843. /**
  99844. * Gets the Color Grading 2D Lookup Texture.
  99845. */
  99846. get: function () {
  99847. return this._imageProcessingConfiguration.colorGradingTexture;
  99848. },
  99849. /**
  99850. * Sets the Color Grading 2D Lookup Texture.
  99851. */
  99852. set: function (value) {
  99853. this.imageProcessingConfiguration.colorGradingTexture = value;
  99854. },
  99855. enumerable: true,
  99856. configurable: true
  99857. });
  99858. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  99859. /**
  99860. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  99861. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  99862. * 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;
  99863. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  99864. */
  99865. get: function () {
  99866. return this.imageProcessingConfiguration.colorCurves;
  99867. },
  99868. /**
  99869. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  99870. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  99871. * 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;
  99872. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  99873. */
  99874. set: function (value) {
  99875. this.imageProcessingConfiguration.colorCurves = value;
  99876. },
  99877. enumerable: true,
  99878. configurable: true
  99879. });
  99880. /**
  99881. * The entire material has been created in order to prevent overdraw.
  99882. * @returns false
  99883. */
  99884. BackgroundMaterial.prototype.needAlphaTesting = function () {
  99885. return true;
  99886. };
  99887. /**
  99888. * The entire material has been created in order to prevent overdraw.
  99889. * @returns true if blending is enable
  99890. */
  99891. BackgroundMaterial.prototype.needAlphaBlending = function () {
  99892. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  99893. };
  99894. /**
  99895. * Checks wether the material is ready to be rendered for a given mesh.
  99896. * @param mesh The mesh to render
  99897. * @param subMesh The submesh to check against
  99898. * @param useInstances Specify wether or not the material is used with instances
  99899. * @returns true if all the dependencies are ready (Textures, Effects...)
  99900. */
  99901. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  99902. var _this = this;
  99903. if (useInstances === void 0) { useInstances = false; }
  99904. if (subMesh.effect && this.isFrozen) {
  99905. if (this._wasPreviouslyReady) {
  99906. return true;
  99907. }
  99908. }
  99909. if (!subMesh._materialDefines) {
  99910. subMesh._materialDefines = new BackgroundMaterialDefines();
  99911. }
  99912. var scene = this.getScene();
  99913. var defines = subMesh._materialDefines;
  99914. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  99915. if (defines._renderId === scene.getRenderId()) {
  99916. return true;
  99917. }
  99918. }
  99919. var engine = scene.getEngine();
  99920. // Lights
  99921. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  99922. defines._needNormals = true;
  99923. // Textures
  99924. if (defines._areTexturesDirty) {
  99925. defines._needUVs = false;
  99926. if (scene.texturesEnabled) {
  99927. if (scene.getEngine().getCaps().textureLOD) {
  99928. defines.TEXTURELODSUPPORT = true;
  99929. }
  99930. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  99931. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  99932. return false;
  99933. }
  99934. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  99935. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  99936. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  99937. defines.OPACITYFRESNEL = this._opacityFresnel;
  99938. }
  99939. else {
  99940. defines.DIFFUSE = false;
  99941. defines.DIFFUSEHASALPHA = false;
  99942. defines.GAMMADIFFUSE = false;
  99943. defines.OPACITYFRESNEL = false;
  99944. }
  99945. var reflectionTexture = this._reflectionTexture;
  99946. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  99947. if (!reflectionTexture.isReadyOrNotBlocking()) {
  99948. return false;
  99949. }
  99950. defines.REFLECTION = true;
  99951. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  99952. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  99953. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  99954. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  99955. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  99956. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  99957. defines.REFLECTIONBGR = this.switchToBGR;
  99958. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  99959. defines.INVERTCUBICMAP = true;
  99960. }
  99961. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  99962. switch (reflectionTexture.coordinatesMode) {
  99963. case BABYLON.Texture.EXPLICIT_MODE:
  99964. defines.REFLECTIONMAP_EXPLICIT = true;
  99965. break;
  99966. case BABYLON.Texture.PLANAR_MODE:
  99967. defines.REFLECTIONMAP_PLANAR = true;
  99968. break;
  99969. case BABYLON.Texture.PROJECTION_MODE:
  99970. defines.REFLECTIONMAP_PROJECTION = true;
  99971. break;
  99972. case BABYLON.Texture.SKYBOX_MODE:
  99973. defines.REFLECTIONMAP_SKYBOX = true;
  99974. break;
  99975. case BABYLON.Texture.SPHERICAL_MODE:
  99976. defines.REFLECTIONMAP_SPHERICAL = true;
  99977. break;
  99978. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  99979. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  99980. break;
  99981. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  99982. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  99983. break;
  99984. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  99985. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  99986. break;
  99987. case BABYLON.Texture.CUBIC_MODE:
  99988. case BABYLON.Texture.INVCUBIC_MODE:
  99989. default:
  99990. defines.REFLECTIONMAP_CUBIC = true;
  99991. break;
  99992. }
  99993. if (this.reflectionFresnel) {
  99994. defines.REFLECTIONFRESNEL = true;
  99995. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  99996. this._reflectionControls.x = this.reflectionAmount;
  99997. this._reflectionControls.y = this.reflectionReflectance0;
  99998. this._reflectionControls.z = this.reflectionReflectance90;
  99999. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  100000. }
  100001. else {
  100002. defines.REFLECTIONFRESNEL = false;
  100003. defines.REFLECTIONFALLOFF = false;
  100004. }
  100005. }
  100006. else {
  100007. defines.REFLECTION = false;
  100008. defines.REFLECTIONFRESNEL = false;
  100009. defines.REFLECTIONFALLOFF = false;
  100010. defines.REFLECTIONBLUR = false;
  100011. defines.REFLECTIONMAP_3D = false;
  100012. defines.REFLECTIONMAP_SPHERICAL = false;
  100013. defines.REFLECTIONMAP_PLANAR = false;
  100014. defines.REFLECTIONMAP_CUBIC = false;
  100015. defines.REFLECTIONMAP_PROJECTION = false;
  100016. defines.REFLECTIONMAP_SKYBOX = false;
  100017. defines.REFLECTIONMAP_EXPLICIT = false;
  100018. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  100019. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  100020. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  100021. defines.INVERTCUBICMAP = false;
  100022. defines.REFLECTIONMAP_OPPOSITEZ = false;
  100023. defines.LODINREFLECTIONALPHA = false;
  100024. defines.GAMMAREFLECTION = false;
  100025. defines.RGBDREFLECTION = false;
  100026. }
  100027. }
  100028. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  100029. defines.USERGBCOLOR = this._useRGBColor;
  100030. defines.NOISE = this._enableNoise;
  100031. }
  100032. if (defines._areLightsDirty) {
  100033. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  100034. }
  100035. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  100036. if (!this._imageProcessingConfiguration.isReady()) {
  100037. return false;
  100038. }
  100039. this._imageProcessingConfiguration.prepareDefines(defines);
  100040. }
  100041. // Misc.
  100042. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  100043. // Values that need to be evaluated on every frame
  100044. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  100045. // Attribs
  100046. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  100047. if (mesh) {
  100048. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  100049. mesh.createNormals(true);
  100050. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  100051. }
  100052. }
  100053. }
  100054. // Get correct effect
  100055. if (defines.isDirty) {
  100056. defines.markAsProcessed();
  100057. scene.resetCachedMaterial();
  100058. // Fallbacks
  100059. var fallbacks = new BABYLON.EffectFallbacks();
  100060. if (defines.FOG) {
  100061. fallbacks.addFallback(0, "FOG");
  100062. }
  100063. if (defines.POINTSIZE) {
  100064. fallbacks.addFallback(1, "POINTSIZE");
  100065. }
  100066. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  100067. if (defines.NUM_BONE_INFLUENCERS > 0) {
  100068. fallbacks.addCPUSkinningFallback(0, mesh);
  100069. }
  100070. //Attributes
  100071. var attribs = [BABYLON.VertexBuffer.PositionKind];
  100072. if (defines.NORMAL) {
  100073. attribs.push(BABYLON.VertexBuffer.NormalKind);
  100074. }
  100075. if (defines.UV1) {
  100076. attribs.push(BABYLON.VertexBuffer.UVKind);
  100077. }
  100078. if (defines.UV2) {
  100079. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  100080. }
  100081. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  100082. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  100083. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  100084. "vFogInfos", "vFogColor", "pointSize",
  100085. "vClipPlane", "mBones",
  100086. "vPrimaryColor", "vPrimaryColorShadow",
  100087. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  100088. "shadowLevel", "alpha",
  100089. "vBackgroundCenter", "vReflectionControl",
  100090. "vDiffuseInfos", "diffuseMatrix",
  100091. ];
  100092. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  100093. var uniformBuffers = ["Material", "Scene"];
  100094. if (BABYLON.ImageProcessingConfiguration) {
  100095. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  100096. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  100097. }
  100098. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  100099. uniformsNames: uniforms,
  100100. uniformBuffersNames: uniformBuffers,
  100101. samplers: samplers,
  100102. defines: defines,
  100103. maxSimultaneousLights: this._maxSimultaneousLights
  100104. });
  100105. var onCompiled = function (effect) {
  100106. if (_this.onCompiled) {
  100107. _this.onCompiled(effect);
  100108. }
  100109. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  100110. };
  100111. var join = defines.toString();
  100112. subMesh.setEffect(scene.getEngine().createEffect("background", {
  100113. attributes: attribs,
  100114. uniformsNames: uniforms,
  100115. uniformBuffersNames: uniformBuffers,
  100116. samplers: samplers,
  100117. defines: join,
  100118. fallbacks: fallbacks,
  100119. onCompiled: onCompiled,
  100120. onError: this.onError,
  100121. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  100122. }, engine), defines);
  100123. this.buildUniformLayout();
  100124. }
  100125. if (!subMesh.effect || !subMesh.effect.isReady()) {
  100126. return false;
  100127. }
  100128. defines._renderId = scene.getRenderId();
  100129. this._wasPreviouslyReady = true;
  100130. return true;
  100131. };
  100132. /**
  100133. * Compute the primary color according to the chosen perceptual color.
  100134. */
  100135. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  100136. if (!this.__perceptualColor) {
  100137. return;
  100138. }
  100139. this._primaryColor.copyFrom(this.__perceptualColor);
  100140. // Revert gamma space.
  100141. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  100142. // Revert image processing configuration.
  100143. if (this._imageProcessingConfiguration) {
  100144. // Revert Exposure.
  100145. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  100146. }
  100147. this._computePrimaryColors();
  100148. };
  100149. /**
  100150. * Compute the highlights and shadow colors according to their chosen levels.
  100151. */
  100152. BackgroundMaterial.prototype._computePrimaryColors = function () {
  100153. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  100154. return;
  100155. }
  100156. // Find the highlight color based on the configuration.
  100157. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  100158. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  100159. // Find the shadow color based on the configuration.
  100160. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  100161. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  100162. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  100163. };
  100164. /**
  100165. * Build the uniform buffer used in the material.
  100166. */
  100167. BackgroundMaterial.prototype.buildUniformLayout = function () {
  100168. // Order is important !
  100169. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  100170. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  100171. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  100172. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  100173. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  100174. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  100175. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  100176. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  100177. this._uniformBuffer.addUniform("pointSize", 1);
  100178. this._uniformBuffer.addUniform("shadowLevel", 1);
  100179. this._uniformBuffer.addUniform("alpha", 1);
  100180. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  100181. this._uniformBuffer.addUniform("vReflectionControl", 4);
  100182. this._uniformBuffer.create();
  100183. };
  100184. /**
  100185. * Unbind the material.
  100186. */
  100187. BackgroundMaterial.prototype.unbind = function () {
  100188. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  100189. this._uniformBuffer.setTexture("diffuseSampler", null);
  100190. }
  100191. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  100192. this._uniformBuffer.setTexture("reflectionSampler", null);
  100193. }
  100194. _super.prototype.unbind.call(this);
  100195. };
  100196. /**
  100197. * Bind only the world matrix to the material.
  100198. * @param world The world matrix to bind.
  100199. */
  100200. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  100201. this._activeEffect.setMatrix("world", world);
  100202. };
  100203. /**
  100204. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  100205. * @param world The world matrix to bind.
  100206. * @param subMesh The submesh to bind for.
  100207. */
  100208. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  100209. var scene = this.getScene();
  100210. var defines = subMesh._materialDefines;
  100211. if (!defines) {
  100212. return;
  100213. }
  100214. var effect = subMesh.effect;
  100215. if (!effect) {
  100216. return;
  100217. }
  100218. this._activeEffect = effect;
  100219. // Matrices
  100220. this.bindOnlyWorldMatrix(world);
  100221. // Bones
  100222. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  100223. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  100224. if (mustRebind) {
  100225. this._uniformBuffer.bindToEffect(effect, "Material");
  100226. this.bindViewProjection(effect);
  100227. var reflectionTexture = this._reflectionTexture;
  100228. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  100229. // Texture uniforms
  100230. if (scene.texturesEnabled) {
  100231. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  100232. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  100233. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  100234. }
  100235. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  100236. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  100237. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  100238. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  100239. }
  100240. }
  100241. if (this.shadowLevel > 0) {
  100242. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  100243. }
  100244. this._uniformBuffer.updateFloat("alpha", this.alpha);
  100245. // Point size
  100246. if (this.pointsCloud) {
  100247. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  100248. }
  100249. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  100250. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  100251. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  100252. }
  100253. else {
  100254. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  100255. }
  100256. }
  100257. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  100258. // Textures
  100259. if (scene.texturesEnabled) {
  100260. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  100261. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  100262. }
  100263. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  100264. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  100265. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  100266. }
  100267. else if (!defines.REFLECTIONBLUR) {
  100268. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  100269. }
  100270. else {
  100271. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  100272. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  100273. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  100274. }
  100275. if (defines.REFLECTIONFRESNEL) {
  100276. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  100277. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  100278. }
  100279. }
  100280. }
  100281. // Clip plane
  100282. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  100283. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  100284. }
  100285. if (mustRebind || !this.isFrozen) {
  100286. if (scene.lightsEnabled) {
  100287. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  100288. }
  100289. // View
  100290. this.bindView(effect);
  100291. // Fog
  100292. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  100293. // image processing
  100294. if (this._imageProcessingConfiguration) {
  100295. this._imageProcessingConfiguration.bind(this._activeEffect);
  100296. }
  100297. }
  100298. this._uniformBuffer.update();
  100299. this._afterBind(mesh, this._activeEffect);
  100300. };
  100301. /**
  100302. * Dispose the material.
  100303. * @param forceDisposeEffect Force disposal of the associated effect.
  100304. * @param forceDisposeTextures Force disposal of the associated textures.
  100305. */
  100306. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  100307. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  100308. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  100309. if (forceDisposeTextures) {
  100310. if (this.diffuseTexture) {
  100311. this.diffuseTexture.dispose();
  100312. }
  100313. if (this.reflectionTexture) {
  100314. this.reflectionTexture.dispose();
  100315. }
  100316. }
  100317. this._renderTargets.dispose();
  100318. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  100319. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  100320. }
  100321. _super.prototype.dispose.call(this, forceDisposeEffect);
  100322. };
  100323. /**
  100324. * Clones the material.
  100325. * @param name The cloned name.
  100326. * @returns The cloned material.
  100327. */
  100328. BackgroundMaterial.prototype.clone = function (name) {
  100329. var _this = this;
  100330. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  100331. };
  100332. /**
  100333. * Serializes the current material to its JSON representation.
  100334. * @returns The JSON representation.
  100335. */
  100336. BackgroundMaterial.prototype.serialize = function () {
  100337. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  100338. serializationObject.customType = "BABYLON.BackgroundMaterial";
  100339. return serializationObject;
  100340. };
  100341. /**
  100342. * Gets the class name of the material
  100343. * @returns "BackgroundMaterial"
  100344. */
  100345. BackgroundMaterial.prototype.getClassName = function () {
  100346. return "BackgroundMaterial";
  100347. };
  100348. /**
  100349. * Parse a JSON input to create back a background material.
  100350. * @param source The JSON data to parse
  100351. * @param scene The scene to create the parsed material in
  100352. * @param rootUrl The root url of the assets the material depends upon
  100353. * @returns the instantiated BackgroundMaterial.
  100354. */
  100355. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  100356. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  100357. };
  100358. /**
  100359. * Standard reflectance value at parallel view angle.
  100360. */
  100361. BackgroundMaterial.StandardReflectance0 = 0.05;
  100362. /**
  100363. * Standard reflectance value at grazing angle.
  100364. */
  100365. BackgroundMaterial.StandardReflectance90 = 0.5;
  100366. __decorate([
  100367. BABYLON.serializeAsColor3()
  100368. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  100369. __decorate([
  100370. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  100371. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  100372. __decorate([
  100373. BABYLON.serializeAsColor3()
  100374. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  100375. __decorate([
  100376. BABYLON.serialize()
  100377. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  100378. __decorate([
  100379. BABYLON.serialize()
  100380. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  100381. __decorate([
  100382. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  100383. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  100384. __decorate([
  100385. BABYLON.serializeAsTexture()
  100386. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  100387. __decorate([
  100388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100389. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  100390. __decorate([
  100391. BABYLON.serialize()
  100392. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  100393. __decorate([
  100394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100395. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  100396. __decorate([
  100397. BABYLON.serializeAsTexture()
  100398. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  100399. __decorate([
  100400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100401. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  100402. __decorate([
  100403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100404. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  100405. __decorate([
  100406. BABYLON.serialize()
  100407. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  100408. __decorate([
  100409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100410. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  100411. __decorate([
  100412. BABYLON.serializeAsVector3()
  100413. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  100414. __decorate([
  100415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100416. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  100417. __decorate([
  100418. BABYLON.serialize()
  100419. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  100420. __decorate([
  100421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100422. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  100423. __decorate([
  100424. BABYLON.serialize()
  100425. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  100426. __decorate([
  100427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100428. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  100429. __decorate([
  100430. BABYLON.serialize()
  100431. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  100432. __decorate([
  100433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100434. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  100435. __decorate([
  100436. BABYLON.serialize()
  100437. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  100438. __decorate([
  100439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100440. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  100441. __decorate([
  100442. BABYLON.serialize()
  100443. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  100444. __decorate([
  100445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100446. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  100447. __decorate([
  100448. BABYLON.serialize()
  100449. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  100450. __decorate([
  100451. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100452. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  100453. __decorate([
  100454. BABYLON.serialize()
  100455. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  100456. __decorate([
  100457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100458. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  100459. __decorate([
  100460. BABYLON.serialize()
  100461. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  100462. __decorate([
  100463. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100464. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  100465. __decorate([
  100466. BABYLON.serialize()
  100467. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  100468. __decorate([
  100469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100470. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  100471. __decorate([
  100472. BABYLON.serializeAsImageProcessingConfiguration()
  100473. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  100474. return BackgroundMaterial;
  100475. }(BABYLON.PushMaterial));
  100476. BABYLON.BackgroundMaterial = BackgroundMaterial;
  100477. })(BABYLON || (BABYLON = {}));
  100478. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  100479. var __assign = (this && this.__assign) || Object.assign || function(t) {
  100480. for (var s, i = 1, n = arguments.length; i < n; i++) {
  100481. s = arguments[i];
  100482. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  100483. t[p] = s[p];
  100484. }
  100485. return t;
  100486. };
  100487. var BABYLON;
  100488. (function (BABYLON) {
  100489. /**
  100490. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  100491. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  100492. * It also helps with the default setup of your imageProcessing configuration.
  100493. */
  100494. var EnvironmentHelper = /** @class */ (function () {
  100495. /**
  100496. * constructor
  100497. * @param options
  100498. * @param scene The scene to add the material to
  100499. */
  100500. function EnvironmentHelper(options, scene) {
  100501. var _this = this;
  100502. this._errorHandler = function (message, exception) {
  100503. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  100504. };
  100505. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  100506. this._scene = scene;
  100507. this.onErrorObservable = new BABYLON.Observable();
  100508. this._setupBackground();
  100509. this._setupImageProcessing();
  100510. }
  100511. /**
  100512. * Creates the default options for the helper.
  100513. */
  100514. EnvironmentHelper._getDefaultOptions = function () {
  100515. return {
  100516. createGround: true,
  100517. groundSize: 15,
  100518. groundTexture: this._groundTextureCDNUrl,
  100519. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  100520. groundOpacity: 0.9,
  100521. enableGroundShadow: true,
  100522. groundShadowLevel: 0.5,
  100523. enableGroundMirror: false,
  100524. groundMirrorSizeRatio: 0.3,
  100525. groundMirrorBlurKernel: 64,
  100526. groundMirrorAmount: 1,
  100527. groundMirrorFresnelWeight: 1,
  100528. groundMirrorFallOffDistance: 0,
  100529. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  100530. groundYBias: 0.00001,
  100531. createSkybox: true,
  100532. skyboxSize: 20,
  100533. skyboxTexture: this._skyboxTextureCDNUrl,
  100534. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  100535. backgroundYRotation: 0,
  100536. sizeAuto: true,
  100537. rootPosition: BABYLON.Vector3.Zero(),
  100538. setupImageProcessing: true,
  100539. environmentTexture: this._environmentTextureCDNUrl,
  100540. cameraExposure: 0.8,
  100541. cameraContrast: 1.2,
  100542. toneMappingEnabled: true,
  100543. };
  100544. };
  100545. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  100546. /**
  100547. * Gets the root mesh created by the helper.
  100548. */
  100549. get: function () {
  100550. return this._rootMesh;
  100551. },
  100552. enumerable: true,
  100553. configurable: true
  100554. });
  100555. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  100556. /**
  100557. * Gets the skybox created by the helper.
  100558. */
  100559. get: function () {
  100560. return this._skybox;
  100561. },
  100562. enumerable: true,
  100563. configurable: true
  100564. });
  100565. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  100566. /**
  100567. * Gets the skybox texture created by the helper.
  100568. */
  100569. get: function () {
  100570. return this._skyboxTexture;
  100571. },
  100572. enumerable: true,
  100573. configurable: true
  100574. });
  100575. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  100576. /**
  100577. * Gets the skybox material created by the helper.
  100578. */
  100579. get: function () {
  100580. return this._skyboxMaterial;
  100581. },
  100582. enumerable: true,
  100583. configurable: true
  100584. });
  100585. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  100586. /**
  100587. * Gets the ground mesh created by the helper.
  100588. */
  100589. get: function () {
  100590. return this._ground;
  100591. },
  100592. enumerable: true,
  100593. configurable: true
  100594. });
  100595. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  100596. /**
  100597. * Gets the ground texture created by the helper.
  100598. */
  100599. get: function () {
  100600. return this._groundTexture;
  100601. },
  100602. enumerable: true,
  100603. configurable: true
  100604. });
  100605. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  100606. /**
  100607. * Gets the ground mirror created by the helper.
  100608. */
  100609. get: function () {
  100610. return this._groundMirror;
  100611. },
  100612. enumerable: true,
  100613. configurable: true
  100614. });
  100615. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  100616. /**
  100617. * Gets the ground mirror render list to helps pushing the meshes
  100618. * you wish in the ground reflection.
  100619. */
  100620. get: function () {
  100621. if (this._groundMirror) {
  100622. return this._groundMirror.renderList;
  100623. }
  100624. return null;
  100625. },
  100626. enumerable: true,
  100627. configurable: true
  100628. });
  100629. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  100630. /**
  100631. * Gets the ground material created by the helper.
  100632. */
  100633. get: function () {
  100634. return this._groundMaterial;
  100635. },
  100636. enumerable: true,
  100637. configurable: true
  100638. });
  100639. /**
  100640. * Updates the background according to the new options
  100641. * @param options
  100642. */
  100643. EnvironmentHelper.prototype.updateOptions = function (options) {
  100644. var newOptions = __assign({}, this._options, options);
  100645. if (this._ground && !newOptions.createGround) {
  100646. this._ground.dispose();
  100647. this._ground = null;
  100648. }
  100649. if (this._groundMaterial && !newOptions.createGround) {
  100650. this._groundMaterial.dispose();
  100651. this._groundMaterial = null;
  100652. }
  100653. if (this._groundTexture) {
  100654. if (this._options.groundTexture != newOptions.groundTexture) {
  100655. this._groundTexture.dispose();
  100656. this._groundTexture = null;
  100657. }
  100658. }
  100659. if (this._skybox && !newOptions.createSkybox) {
  100660. this._skybox.dispose();
  100661. this._skybox = null;
  100662. }
  100663. if (this._skyboxMaterial && !newOptions.createSkybox) {
  100664. this._skyboxMaterial.dispose();
  100665. this._skyboxMaterial = null;
  100666. }
  100667. if (this._skyboxTexture) {
  100668. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  100669. this._skyboxTexture.dispose();
  100670. this._skyboxTexture = null;
  100671. }
  100672. }
  100673. if (this._groundMirror && !newOptions.enableGroundMirror) {
  100674. this._groundMirror.dispose();
  100675. this._groundMirror = null;
  100676. }
  100677. if (this._scene.environmentTexture) {
  100678. if (this._options.environmentTexture != newOptions.environmentTexture) {
  100679. this._scene.environmentTexture.dispose();
  100680. }
  100681. }
  100682. this._options = newOptions;
  100683. this._setupBackground();
  100684. this._setupImageProcessing();
  100685. };
  100686. /**
  100687. * Sets the primary color of all the available elements.
  100688. * @param color the main color to affect to the ground and the background
  100689. */
  100690. EnvironmentHelper.prototype.setMainColor = function (color) {
  100691. if (this.groundMaterial) {
  100692. this.groundMaterial.primaryColor = color;
  100693. }
  100694. if (this.skyboxMaterial) {
  100695. this.skyboxMaterial.primaryColor = color;
  100696. }
  100697. if (this.groundMirror) {
  100698. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  100699. }
  100700. };
  100701. /**
  100702. * Setup the image processing according to the specified options.
  100703. */
  100704. EnvironmentHelper.prototype._setupImageProcessing = function () {
  100705. if (this._options.setupImageProcessing) {
  100706. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  100707. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  100708. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  100709. this._setupEnvironmentTexture();
  100710. }
  100711. };
  100712. /**
  100713. * Setup the environment texture according to the specified options.
  100714. */
  100715. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  100716. if (this._scene.environmentTexture) {
  100717. return;
  100718. }
  100719. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  100720. this._scene.environmentTexture = this._options.environmentTexture;
  100721. return;
  100722. }
  100723. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  100724. this._scene.environmentTexture = environmentTexture;
  100725. };
  100726. /**
  100727. * Setup the background according to the specified options.
  100728. */
  100729. EnvironmentHelper.prototype._setupBackground = function () {
  100730. if (!this._rootMesh) {
  100731. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  100732. }
  100733. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  100734. var sceneSize = this._getSceneSize();
  100735. if (this._options.createGround) {
  100736. this._setupGround(sceneSize);
  100737. this._setupGroundMaterial();
  100738. this._setupGroundDiffuseTexture();
  100739. if (this._options.enableGroundMirror) {
  100740. this._setupGroundMirrorTexture(sceneSize);
  100741. }
  100742. this._setupMirrorInGroundMaterial();
  100743. }
  100744. if (this._options.createSkybox) {
  100745. this._setupSkybox(sceneSize);
  100746. this._setupSkyboxMaterial();
  100747. this._setupSkyboxReflectionTexture();
  100748. }
  100749. this._rootMesh.position.x = sceneSize.rootPosition.x;
  100750. this._rootMesh.position.z = sceneSize.rootPosition.z;
  100751. this._rootMesh.position.y = sceneSize.rootPosition.y;
  100752. };
  100753. /**
  100754. * Get the scene sizes according to the setup.
  100755. */
  100756. EnvironmentHelper.prototype._getSceneSize = function () {
  100757. var _this = this;
  100758. var groundSize = this._options.groundSize;
  100759. var skyboxSize = this._options.skyboxSize;
  100760. var rootPosition = this._options.rootPosition;
  100761. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  100762. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  100763. }
  100764. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  100765. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  100766. });
  100767. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  100768. if (this._options.sizeAuto) {
  100769. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  100770. this._scene.activeCamera.upperRadiusLimit) {
  100771. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  100772. skyboxSize = groundSize;
  100773. }
  100774. var sceneDiagonalLenght = sceneDiagonal.length();
  100775. if (sceneDiagonalLenght > groundSize) {
  100776. groundSize = sceneDiagonalLenght * 2;
  100777. skyboxSize = groundSize;
  100778. }
  100779. // 10 % bigger.
  100780. groundSize *= 1.1;
  100781. skyboxSize *= 1.5;
  100782. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  100783. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  100784. }
  100785. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  100786. };
  100787. /**
  100788. * Setup the ground according to the specified options.
  100789. */
  100790. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  100791. var _this = this;
  100792. if (!this._ground || this._ground.isDisposed()) {
  100793. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  100794. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  100795. this._ground.parent = this._rootMesh;
  100796. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  100797. }
  100798. this._ground.receiveShadows = this._options.enableGroundShadow;
  100799. };
  100800. /**
  100801. * Setup the ground material according to the specified options.
  100802. */
  100803. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  100804. if (!this._groundMaterial) {
  100805. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  100806. }
  100807. this._groundMaterial.alpha = this._options.groundOpacity;
  100808. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  100809. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  100810. this._groundMaterial.primaryColor = this._options.groundColor;
  100811. this._groundMaterial.useRGBColor = false;
  100812. this._groundMaterial.enableNoise = true;
  100813. if (this._ground) {
  100814. this._ground.material = this._groundMaterial;
  100815. }
  100816. };
  100817. /**
  100818. * Setup the ground diffuse texture according to the specified options.
  100819. */
  100820. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  100821. if (!this._groundMaterial) {
  100822. return;
  100823. }
  100824. if (this._groundTexture) {
  100825. return;
  100826. }
  100827. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  100828. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  100829. return;
  100830. }
  100831. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  100832. diffuseTexture.gammaSpace = false;
  100833. diffuseTexture.hasAlpha = true;
  100834. this._groundMaterial.diffuseTexture = diffuseTexture;
  100835. };
  100836. /**
  100837. * Setup the ground mirror texture according to the specified options.
  100838. */
  100839. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  100840. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100841. if (!this._groundMirror) {
  100842. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  100843. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  100844. this._groundMirror.anisotropicFilteringLevel = 1;
  100845. this._groundMirror.wrapU = wrapping;
  100846. this._groundMirror.wrapV = wrapping;
  100847. this._groundMirror.gammaSpace = false;
  100848. if (this._groundMirror.renderList) {
  100849. for (var i = 0; i < this._scene.meshes.length; i++) {
  100850. var mesh = this._scene.meshes[i];
  100851. if (mesh !== this._ground &&
  100852. mesh !== this._skybox &&
  100853. mesh !== this._rootMesh) {
  100854. this._groundMirror.renderList.push(mesh);
  100855. }
  100856. }
  100857. }
  100858. }
  100859. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  100860. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  100861. };
  100862. /**
  100863. * Setup the ground to receive the mirror texture.
  100864. */
  100865. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  100866. if (this._groundMaterial) {
  100867. this._groundMaterial.reflectionTexture = this._groundMirror;
  100868. this._groundMaterial.reflectionFresnel = true;
  100869. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  100870. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  100871. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  100872. }
  100873. };
  100874. /**
  100875. * Setup the skybox according to the specified options.
  100876. */
  100877. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  100878. var _this = this;
  100879. if (!this._skybox || this._skybox.isDisposed()) {
  100880. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  100881. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  100882. }
  100883. this._skybox.parent = this._rootMesh;
  100884. };
  100885. /**
  100886. * Setup the skybox material according to the specified options.
  100887. */
  100888. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  100889. if (!this._skybox) {
  100890. return;
  100891. }
  100892. if (!this._skyboxMaterial) {
  100893. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  100894. }
  100895. this._skyboxMaterial.useRGBColor = false;
  100896. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  100897. this._skyboxMaterial.enableNoise = true;
  100898. this._skybox.material = this._skyboxMaterial;
  100899. };
  100900. /**
  100901. * Setup the skybox reflection texture according to the specified options.
  100902. */
  100903. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  100904. if (!this._skyboxMaterial) {
  100905. return;
  100906. }
  100907. if (this._skyboxTexture) {
  100908. return;
  100909. }
  100910. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  100911. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  100912. return;
  100913. }
  100914. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  100915. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  100916. this._skyboxTexture.gammaSpace = false;
  100917. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  100918. };
  100919. /**
  100920. * Dispose all the elements created by the Helper.
  100921. */
  100922. EnvironmentHelper.prototype.dispose = function () {
  100923. if (this._groundMaterial) {
  100924. this._groundMaterial.dispose(true, true);
  100925. }
  100926. if (this._skyboxMaterial) {
  100927. this._skyboxMaterial.dispose(true, true);
  100928. }
  100929. this._rootMesh.dispose(false);
  100930. };
  100931. /**
  100932. * Default ground texture URL.
  100933. */
  100934. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  100935. /**
  100936. * Default skybox texture URL.
  100937. */
  100938. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  100939. /**
  100940. * Default environment texture URL.
  100941. */
  100942. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  100943. return EnvironmentHelper;
  100944. }());
  100945. BABYLON.EnvironmentHelper = EnvironmentHelper;
  100946. })(BABYLON || (BABYLON = {}));
  100947. //# sourceMappingURL=babylon.environmentHelper.js.map
  100948. var BABYLON;
  100949. (function (BABYLON) {
  100950. /**
  100951. * This class is made for on one-liner static method to help creating particle systems.
  100952. */
  100953. var ParticleHelper = /** @class */ (function () {
  100954. function ParticleHelper() {
  100955. }
  100956. /**
  100957. * This is the main static method (one-liner) of this helper to create different particle systems.
  100958. * @param type This string represents the type to the particle system to create
  100959. * @param emitter The object where the particle system will start to emit from.
  100960. * @param scene The scene where the particle system should live.
  100961. * @param gpu If the system will use gpu.
  100962. * @returns the ParticleSystem created.
  100963. */
  100964. ParticleHelper.CreateAsync = function (type, emitter, scene, gpu) {
  100965. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  100966. if (gpu === void 0) { gpu = false; }
  100967. return new Promise(function (resolve, reject) {
  100968. if (!scene) {
  100969. scene = BABYLON.Engine.LastCreatedScene;
  100970. ;
  100971. }
  100972. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  100973. return reject("Particle system with GPU is not supported.");
  100974. }
  100975. BABYLON.Tools.LoadFile(ParticleHelper._baseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  100976. var newData = JSON.parse(data.toString());
  100977. return resolve(ParticleHelper.CreateSystem(newData, scene, emitter));
  100978. }, undefined, undefined, undefined, function (req, exception) {
  100979. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  100980. });
  100981. });
  100982. };
  100983. /**
  100984. * Static function used to create a new particle system from a IParticleSystemData
  100985. * @param data defines the source data
  100986. * @param scene defines the hosting scene
  100987. * @param emitter defines the particle emitter
  100988. * @returns a new ParticleSystem based on referenced data
  100989. */
  100990. ParticleHelper.CreateSystem = function (data, scene, emitter) {
  100991. // Create a particle system
  100992. var system = new BABYLON.ParticleSystem(data.type, data.capacity, scene);
  100993. // Where the particles come from
  100994. system.emitter = emitter; // the starting object, the emitter
  100995. ParticleHelper.UpdateSystem(system, data, scene);
  100996. return system;
  100997. };
  100998. /**
  100999. * Static function used to update a particle system from a IParticleSystemData
  101000. * @param system defines the particle system to update
  101001. * @param data defines the source data
  101002. * @param scene defines the hosting scene
  101003. */
  101004. ParticleHelper.UpdateSystem = function (system, data, scene) {
  101005. // Texture of each particle
  101006. if (data.textureFile) {
  101007. system.particleTexture = new BABYLON.Texture(ParticleHelper._baseAssetsUrl + "/textures/" + data.textureFile, scene);
  101008. }
  101009. // Colors of all particles
  101010. system.color1 = new BABYLON.Color4(data.color1.r, data.color1.g, data.color1.b, data.color1.a);
  101011. system.color2 = new BABYLON.Color4(data.color2.r, data.color2.g, data.color2.b, data.color2.a);
  101012. system.colorDead = new BABYLON.Color4(data.colorDead.r, data.colorDead.g, data.colorDead.b, data.colorDead.a);
  101013. // Size of each particle (random between...
  101014. system.minSize = data.minSize;
  101015. system.maxSize = data.maxSize;
  101016. system.minScaleX = data.minScaleX;
  101017. system.maxScaleX = data.maxScaleX;
  101018. system.minScaleY = data.minScaleY;
  101019. system.maxScaleY = data.maxScaleY;
  101020. // Life time of each particle (random between...
  101021. system.minLifeTime = data.minLifeTime;
  101022. system.maxLifeTime = data.maxLifeTime;
  101023. // Emission rate
  101024. system.emitRate = data.emitRate;
  101025. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  101026. system.blendMode = data.blendMode;
  101027. // Set the gravity of all particles
  101028. system.gravity = new BABYLON.Vector3(data.gravity.x, data.gravity.y, data.gravity.z);
  101029. // Angular speed, in radians
  101030. system.minAngularSpeed = data.minAngularSpeed;
  101031. system.maxAngularSpeed = data.maxAngularSpeed;
  101032. // Speed
  101033. system.minEmitPower = data.minEmitPower;
  101034. system.maxEmitPower = data.maxEmitPower;
  101035. system.updateSpeed = data.updateSpeed;
  101036. switch (data.emitterType) {
  101037. case "box":
  101038. if (!data.direction1 || !data.direction2) {
  101039. throw new Error("Directions are missing in this particle system.");
  101040. }
  101041. if (!data.minEmitBox || !data.maxEmitBox) {
  101042. throw new Error("EmitBox is missing in this particle system.");
  101043. }
  101044. system.createBoxEmitter(new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z), new BABYLON.Vector3(data.minEmitBox.x, data.minEmitBox.y, data.minEmitBox.z), new BABYLON.Vector3(data.maxEmitBox.x, data.maxEmitBox.y, data.maxEmitBox.z));
  101045. break;
  101046. case "sphere":
  101047. system.createSphereEmitter(data.radius);
  101048. break;
  101049. case "directed_sphere":
  101050. if (!data.direction1 || !data.direction2) {
  101051. throw new Error("Directions are missing in this particle system.");
  101052. }
  101053. system.createDirectedSphereEmitter(data.radius, new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z));
  101054. break;
  101055. case "cone":
  101056. system.createConeEmitter(data.radius, data.angle);
  101057. break;
  101058. default:
  101059. break;
  101060. }
  101061. };
  101062. /**
  101063. * Static function used to export a particle system to a IParticleSystemData variable.
  101064. * Please note that texture file name is not exported and must be added manually
  101065. * @param system defines the particle system to export
  101066. */
  101067. ParticleHelper.ExportSystem = function (system) {
  101068. var outData = {};
  101069. // Colors of all particles
  101070. outData.color1 = { r: system.color1.r, g: system.color1.g, b: system.color1.b, a: system.color1.a };
  101071. outData.color2 = { r: system.color2.r, g: system.color2.g, b: system.color2.b, a: system.color2.a };
  101072. outData.colorDead = { r: system.colorDead.r, g: system.colorDead.g, b: system.colorDead.b, a: system.colorDead.a };
  101073. // Size of each particle (random between...
  101074. outData.minSize = system.minSize;
  101075. outData.maxSize = system.maxSize;
  101076. outData.minScaleX = system.minScaleX;
  101077. outData.maxScaleX = system.maxScaleX;
  101078. outData.minScaleY = system.minScaleY;
  101079. outData.maxScaleY = system.maxScaleY;
  101080. // Life time of each particle (random between...
  101081. outData.minLifeTime = system.minLifeTime;
  101082. outData.maxLifeTime = system.maxLifeTime;
  101083. // Emission rate
  101084. outData.emitRate = system.emitRate;
  101085. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  101086. outData.blendMode = system.blendMode;
  101087. // Set the gravity of all particles
  101088. outData.gravity = { x: system.gravity.x, y: system.gravity.y, z: system.gravity.z };
  101089. // Angular speed, in radians
  101090. outData.minAngularSpeed = system.minAngularSpeed;
  101091. outData.maxAngularSpeed = system.maxAngularSpeed;
  101092. // Speed
  101093. outData.minEmitPower = system.minEmitPower;
  101094. outData.maxEmitPower = system.maxEmitPower;
  101095. outData.updateSpeed = system.updateSpeed;
  101096. switch (system.particleEmitterType.getClassName()) {
  101097. case "BoxEmitter":
  101098. outData.emitterType = "box";
  101099. outData.direction1 = { x: system.direction1.x, y: system.direction1.y, z: system.direction1.z };
  101100. outData.direction2 = { x: system.direction2.x, y: system.direction2.y, z: system.direction2.z };
  101101. outData.minEmitBox = { x: system.minEmitBox.x, y: system.minEmitBox.y, z: system.minEmitBox.z };
  101102. outData.maxEmitBox = { x: system.maxEmitBox.x, y: system.maxEmitBox.y, z: system.maxEmitBox.z };
  101103. break;
  101104. case "SphereParticleEmitter":
  101105. outData.emitterType = "sphere";
  101106. outData.radius = system.particleEmitterType.radius;
  101107. break;
  101108. case "SphereDirectedParticleEmitter":
  101109. outData.emitterType = "directed_sphere";
  101110. var sphereDirectedParticleEmitter = system.particleEmitterType;
  101111. outData.radius = sphereDirectedParticleEmitter.radius;
  101112. outData.direction1 = { x: sphereDirectedParticleEmitter.direction1.x, y: sphereDirectedParticleEmitter.direction1.y, z: sphereDirectedParticleEmitter.direction1.z };
  101113. outData.direction2 = { x: sphereDirectedParticleEmitter.direction2.x, y: sphereDirectedParticleEmitter.direction2.y, z: sphereDirectedParticleEmitter.direction2.z };
  101114. break;
  101115. case "ConeEmitter":
  101116. outData.emitterType = "cone";
  101117. outData.radius = system.particleEmitterType.radius;
  101118. outData.angle = system.particleEmitterType.angle;
  101119. break;
  101120. default:
  101121. break;
  101122. }
  101123. return outData;
  101124. };
  101125. /**
  101126. * Base Assets URL.
  101127. */
  101128. ParticleHelper._baseAssetsUrl = "https://assets.babylonjs.com/particles";
  101129. return ParticleHelper;
  101130. }());
  101131. BABYLON.ParticleHelper = ParticleHelper;
  101132. })(BABYLON || (BABYLON = {}));
  101133. //# sourceMappingURL=babylon.particleHelper.js.map
  101134. var BABYLON;
  101135. (function (BABYLON) {
  101136. /**
  101137. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  101138. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  101139. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  101140. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  101141. */
  101142. var VideoDome = /** @class */ (function (_super) {
  101143. __extends(VideoDome, _super);
  101144. /**
  101145. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  101146. * @param name Element's name, child elements will append suffixes for their own names.
  101147. * @param urlsOrVideo defines the url(s) or the video element to use
  101148. * @param options An object containing optional or exposed sub element properties
  101149. */
  101150. function VideoDome(name, urlsOrVideo, options, scene) {
  101151. var _this = _super.call(this, name, scene) || this;
  101152. // set defaults and manage values
  101153. name = name || "videoDome";
  101154. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  101155. options.clickToPlay = Boolean(options.clickToPlay);
  101156. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  101157. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  101158. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  101159. // create
  101160. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  101161. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  101162. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  101163. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  101164. flat: false,
  101165. radius: options.size,
  101166. subdivisions: options.resolution,
  101167. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  101168. }, scene);
  101169. // configure material
  101170. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  101171. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  101172. material.reflectionTexture = _this._videoTexture;
  101173. material.useEquirectangularFOV = true;
  101174. material.fovMultiplier = 1.0;
  101175. // configure mesh
  101176. _this._mesh.material = material;
  101177. _this._mesh.parent = _this;
  101178. // optional configuration
  101179. if (options.clickToPlay) {
  101180. scene.onPointerUp = function () {
  101181. _this._videoTexture.video.play();
  101182. };
  101183. }
  101184. return _this;
  101185. }
  101186. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  101187. /**
  101188. * Gets the video texture being displayed on the sphere
  101189. */
  101190. get: function () {
  101191. return this._videoTexture;
  101192. },
  101193. enumerable: true,
  101194. configurable: true
  101195. });
  101196. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  101197. /**
  101198. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  101199. * Also see the options.resolution property.
  101200. */
  101201. get: function () {
  101202. return this._material.fovMultiplier;
  101203. },
  101204. set: function (value) {
  101205. this._material.fovMultiplier = value;
  101206. },
  101207. enumerable: true,
  101208. configurable: true
  101209. });
  101210. /**
  101211. * Releases resources associated with this node.
  101212. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  101213. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  101214. */
  101215. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  101216. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  101217. this._videoTexture.dispose();
  101218. this._mesh.dispose();
  101219. this._material.dispose();
  101220. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  101221. };
  101222. return VideoDome;
  101223. }(BABYLON.Node));
  101224. BABYLON.VideoDome = VideoDome;
  101225. })(BABYLON || (BABYLON = {}));
  101226. //# sourceMappingURL=babylon.videoDome.js.map
  101227. var BABYLON;
  101228. (function (BABYLON) {
  101229. /**
  101230. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  101231. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  101232. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  101233. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  101234. */
  101235. var PhotoDome = /** @class */ (function (_super) {
  101236. __extends(PhotoDome, _super);
  101237. /**
  101238. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  101239. * @param name Element's name, child elements will append suffixes for their own names.
  101240. * @param urlsOfPhoto define the url of the photo to display
  101241. * @param options An object containing optional or exposed sub element properties
  101242. */
  101243. function PhotoDome(name, urlOfPhoto, options, scene) {
  101244. var _this = _super.call(this, name, scene) || this;
  101245. // set defaults and manage values
  101246. name = name || "photoDome";
  101247. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  101248. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  101249. // create
  101250. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  101251. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  101252. flat: false,
  101253. radius: options.size,
  101254. subdivisions: options.resolution,
  101255. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  101256. }, scene);
  101257. // configure material
  101258. material.useEquirectangularFOV = true;
  101259. material.fovMultiplier = 1.0;
  101260. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene);
  101261. // configure mesh
  101262. _this._mesh.material = material;
  101263. _this._mesh.parent = _this;
  101264. return _this;
  101265. }
  101266. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  101267. /**
  101268. * Gets or sets the texture being displayed on the sphere
  101269. */
  101270. get: function () {
  101271. return this._photoTexture;
  101272. },
  101273. set: function (value) {
  101274. if (this._photoTexture === value) {
  101275. return;
  101276. }
  101277. this._photoTexture = value;
  101278. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  101279. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  101280. this._material.reflectionTexture = this._photoTexture;
  101281. },
  101282. enumerable: true,
  101283. configurable: true
  101284. });
  101285. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  101286. /**
  101287. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  101288. * Also see the options.resolution property.
  101289. */
  101290. get: function () {
  101291. return this._material.fovMultiplier;
  101292. },
  101293. set: function (value) {
  101294. this._material.fovMultiplier = value;
  101295. },
  101296. enumerable: true,
  101297. configurable: true
  101298. });
  101299. /**
  101300. * Releases resources associated with this node.
  101301. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  101302. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  101303. */
  101304. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  101305. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  101306. this._photoTexture.dispose();
  101307. this._mesh.dispose();
  101308. this._material.dispose();
  101309. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  101310. };
  101311. return PhotoDome;
  101312. }(BABYLON.Node));
  101313. BABYLON.PhotoDome = PhotoDome;
  101314. })(BABYLON || (BABYLON = {}));
  101315. //# sourceMappingURL=babylon.photoDome.js.map
  101316. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nvec3 worldPos=position+alignedCorner; \ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\nin vec4 color;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin vec2 angle;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\nvec2 cornerPos=offset*size.yz*size.x;\n#ifdef BILLBOARD\n\nvec4 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.y=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nrotatedCorner.z=0.;\nrotatedCorner.w=0.;\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+rotatedCorner);\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nvec3 yaxis=normalize(initialDirection);\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\n\nvec4 viewPosition=view*vec4(position+alignedCorner,1.0); \ngl_Position=projection*viewPosition;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform vec2 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float coneAngle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin vec3 size;\nin vec4 color;\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin vec2 angle;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout vec3 outSize;\nout vec4 outColor;\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\nout vec2 outAngle;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,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;\noutColor=vec4(0.,0.,0.,0.);\noutSize=vec3(0.,0.,0.);\n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif \noutDirection=direction;\noutAngle=angle;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a;\n\noutColor=color1+(color2-color1)*randoms.b;\n\noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=0.;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.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(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (coneAngle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(direction,0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\noutDirection=direction+gravity*timeDelta;\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  101317. 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=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\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=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\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);
  101318. globalObject["BABYLON"] = BABYLON;
  101319. 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 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 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 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 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 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 VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;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 VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;var VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;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 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 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 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 ;
  101320. 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,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,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,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,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,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,VRDistortionCorrectionPostProcess,AnaglyphPostProcess,StereoscopicInterlacePostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationGamepadCamera,VRDeviceOrientationArcRotateCamera,AnaglyphFreeCamera,AnaglyphArcRotateCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicFreeCamera,StereoscopicArcRotateCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,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,EffectLayer,HighlightLayer,GlowLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,NullEngineOptions,NullEngine,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,ParticleHelper,VideoDome,PhotoDome,Space ,Orientation ,AnimationKeyInterpolation ,WorkerTaskType ,WorkerReplyType ,Xbox360Button ,Xbox360Dpad ,PoseEnabledControllerType ,DepthOfFieldEffectBlurLevel ,TonemappingOperator ,PhysicsRadialImpulseFalloff ,PhysicsUpdraftMode ,Debug ,JoystickAxis ,SimplificationType ,AssetTaskState };